MCS97
MCS97

Reputation: 11

Run a process to work on a particular function

I got a code in C that contains main function and another function, And I made a fork to create another process. I want to make the new process perform only the function and once it finishes executing it will die.

I searched solution but I didn't find.

Upvotes: 1

Views: 1694

Answers (1)

H.S.
H.S.

Reputation: 12669

You can do:

#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;
}

Upvotes: 6

Related Questions