运行一个进程来处理特定的函数

0 c operating-system process

我在C中得到了一个包含main函数和另一个函数的代码,并且我创建了一个fork来创建另一个进程.我想让新进程只执行函数,一旦完成执行就会死掉.

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

H.S*_*.S. 5

你可以做:

#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;
}
Run Code Online (Sandbox Code Playgroud)