【问题标题】:Run a process to work on a particular function运行进程以处理特定功能
【发布时间】:2018-08-30 18:00:01
【问题描述】:

我用 C 语言编写了一个包含 main 函数和另一个函数的代码,并且我创建了一个 fork 来创建另一个进程。我想让新进程只执行该功能,一旦执行完毕,它就会死掉。

我搜索了解决方案,但没有找到。

【问题讨论】:

  • 让子进程调用函数并在它返回后调用exit()
  • 退出子进程就像退出父进程一样:调用exit或从main返回。

标签: c process operating-system


【解决方案1】:

你可以这样做:

#include <stdio.h>
#include <stdlib.h>

void fun()
{
     printf ("In fun\n");
     // Do your stuff
     // ....
}

int main(void)
{
   pid_t pid = fork();

   if (pid == -1) {
      perror("fork failed");
      exit(EXIT_FAILURE);
   }
   else if (pid == 0) {
      // Child process
      fun();   // Calling function in child process
      exit(EXIT_SUCCESS);
   }
   else {
      // Parent process
      int status;
      // Wait for child
      waitpid(pid, &status, 0);
   }
   return EXIT_SUCCESS;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-21
    • 2012-08-25
    • 2019-10-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多