The use of fork function in linux

  
        

When you started learning system programming, you learned about the use of fork and recorded it for your own learning.

The fork function is used to create a new process,

#include # Include

#include

#include

int main(void)

{

pid_t pid;

Char *message;

int n;

pid = fork();

if (pid < 0) {

perror("fork Failed");

exit(1);

}

if (pid == 0) {

message = "This is the child \ ";

n = 3;

} else {

message = "This is the parent\ ";

n = 6 ;

}

for(; n > 0; n--) {

printf("%s",message);

Sleep(1);

}

return 0;

}

Program run result:

Return value: Subprocess return 0, the parent process returns the id of the child process, if it fails, it returns -1;

The fork function is called once but returns twice. The only difference between the two returns is that the return value of the child process is 0, and the parent The process return value is the process ID number of the new process. The reason to return the child process ID to the parent process is that because there can be more than one child process of a process, and no function allows a process to obtain the process ID number of all its child processes. The reason the fork function returns the child process to 0 is that a process will only have one parent process, so the child process can always call getppid to get the process ID of its parent process

Copyright © Windows knowledge All Rights Reserved