如何使用exec()系统调用返回数字的平方并将其存储到文件中?

时间:2018-08-01 14:40:10

标签: c system-calls

由用户在命令行中给出一个数字,我需要返回该数字的平方并将其存储到名为child.txt的文件中,但是我需要通过创建子进程并使用{ {1}}。我该怎么做?这是我到目前为止的内容:

exec()

我应该将什么参数传递给#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <unistd.h> int main(int argc, char *argv[]) { FILE *f; f = fopen("child.txt", "w"); int pid = fork(); square(argv); exec(); // This is wrong, I need to fix this return 0; } int square(char *argv[]) { int i; i = atoi(argv[1]); return i*i; } ?我已经看到了其他示例,其中exec()具有诸如exec()echo之类的参数,但是是否可以通过某种方式传递我编写的-ls函数?

2 个答案:

答案 0 :(得分:1)

由于许多原因,这真是一个可怕的主意。 但您当然可以做到:

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>

int square(const char *arg) {
   int i;
   i = strtoll(arg, NULL, 10);
   return i*i;
}

int main(int argc, char *argv[]) {
        FILE *f;
        char cmd[128];
        int rv;

        if( argc < 3 ) {
                fputs( "Please specify target file and integer to square\n", stderr);
                exit(EXIT_FAILURE);
        }

        f = fopen(argv[1], "w");
        if( f == NULL ) {
                perror(argv[1]);
                exit(EXIT_FAILURE);
        }
        rv = snprintf(cmd, sizeof cmd, "echo %d >& %d", square(argv[2]), fileno(f));
        if( rv >= sizeof cmd ) {
                fputs( "Choose a smaller int\n", stderr);
                exit(EXIT_FAILURE);
        }

        execl("/bin/sh", "sh", "-c", cmd, NULL);
        perror("execl");
        return EXIT_FAILURE;
}

但是请注意,如果这是一项作业,并且被告知您使用exec*,那么此解决方案将是F等级。这不是您应该做的。 (至少我希望不会。如果这是目标,那么这是一个可怕的任务。)

答案 1 :(得分:0)

如果要在主线程中进行某些计算,则可以创建线程并将其分离。 如果使用c11编译器,则可以使用threads.h。 thrd_create将创建您的线程,thrd_detach会将其与主进程分离。

如果您的编译器不支持c11,则可以使用本机多重读取选项。

#include <pthread.h>(对于Unix系统)

#include <windows.h(对于Windows)