【问题标题】:How to use exec() system call to return the square of a number and store it to a file?如何使用 exec() 系统调用返回数字的平方并将其存储到文件中?
【发布时间】:2018-08-01 14:40:09
【问题描述】:

给定用户在命令行中的一个数字,我需要返回该数字的平方并将其存储到一个名为 child.txt 的文件中,但我需要通过创建一个子进程并使用 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 等参数,但是否有可能以某种方式传入我编写的 square() 函数?

【问题讨论】:

  • exec() 实际上是用来启动一个可执行文件square 本身实际上是一个函数,所以你需要做的就是以某种方式使其成为自己的可执行文件。
  • 你的问题就像问如何用锤子给灯泡供电。这真的没有任何意义。 为什么你需要使用exec()
  • 很抱歉,不清楚,我在作业上得到了两行指令。我可以制作一个单独的 square.c,编译它并将其转换为可执行文件,我只需要一个示例,说明如何将 exec() 与此可执行文件一起使用,然后将输出存储到文件中。
  • 我需要使用 exec() 才能理解它,只是想学习一下。
  • 阅读 execve(2) & exec(3) man pages

标签: c system-calls


【解决方案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 成绩。这不是你应该做的。 (至少我希望不是。如果这是目标,那么这是一个糟糕的任务。)

【讨论】:

  • 是的,感谢您抽出宝贵时间查看它
【解决方案2】:

如果你想在主线程之外进行一些计算,你可以创建线程并分离它。 如果你使用 c11 编译器,你可以使用threads.h。 thrd_create 将创建您的线程,thrd_detach 将其与主进程分离。

如果您的编译器不支持 c11,您可以使用原生多线程选项。

#include &lt;pthread.h&gt; 用于 Unix 系统

#include &lt;windows.h 用于 Windows

【讨论】:

    猜你喜欢
    • 2017-07-27
    • 2021-07-10
    • 2016-12-09
    • 2016-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-19
    • 2017-08-30
    相关资源
    最近更新 更多