Fork and exit process

来源:互联网 发布:mac lovelorn试色 编辑:程序博客网 时间:2024/06/02 22:22

Int fork():

One process can create another process that is child process through fork(). fork() is called once but return twice. The different of twice return is returned 0 by child process but child ID by parent process.

  The child process is the copy of the parent process, it gets the copy of the parent such as data space,stack,heap resource. So, the child process has the copy of the space, it can't share these resource with parent, only share the code segment.

 

The usage of the fork(): 

int pid = fork():

if(pid == 0)

    printf("This is child process.")

else if(pid > 0)

    printf("This is parent process");

    //you can get the pid from the parent process.

 

If you want to launch a process in another process, you can create a child process to do it through fork(). 

 

 

Exit(int status);

 

If you exit you child process, the parent process can get the status and child process ID(This is a good way to get the child process ID when the child process exit.)

 

The following code is the example of exit() and fork()

 

The important Point: exit(status)--the status reserve the last 8bit int( status & 0377)

(If you status is greater than 255, you don't get the correct status code in parent process.)