多进程学习2

来源:互联网 发布:淘宝买家黑名单设置 编辑:程序博客网 时间:2024/05/06 18:16

多进程学习1讲了fork和execl的用法, 那么system和execl有啥区别呢?

下面是system的例子, code和 上一篇文章一致。

 

main1:

void main( void ) { pid_t child = fork();    if ( child == -1 )     // this is the child process    {    printf( "fork err.\n" );exit(EXIT_FAILURE);    } else if ( child == 0 )     // this is the child process    {    sleep(2);int errno;    printf( "in child process.\n" );  printf("\tchild pid = %d\n",getpid());  printf("\tchild ppid = %d\n",getppid());          //errno = execl( "/home/xa00087/temp/test/main/main2", "main2", "test1", "test2", "test3",( char * )NULL );system("/home/xa00087/temp/test/main/main2");//printf( "execl failed, error code: %d(%s)", errno, strerror( errno ) );printf("child process exit\n");  exit(EXIT_SUCCESS);    } else {printf( "in parent process.\n" );printf("\tparent pid = %d\n",getpid());          printf("\tparent ppid = %d\n",getppid()); int status;    waitpid( child, &status, 0 );printf("WIFEXITED( status ) = %d\n", WIFEXITED( status )); printf("WEXITSTATUS( status ) = %d\n", WEXITSTATUS( status )); sleep(10);printf("parent process exit\n"); }exit(EXIT_SUCCESS);  } 


 

main2:

void main(int argc,char *argv[]){ int i = 0;printf("\tmain2 pid = %d\n",getpid());  printf("\tmain2 ppid = %d\n",getppid()); printf("argc = %d \n", argc);for (i=0; i<argc; i++) {printf("argv[%d]=%s \n", i,  argv[i]);}char mine[128];i= 5;while (i-- >0) {sleep(1);printf("this is in main2 progress! \n");}printf("main2 progress exit! \n");


运行结果:

in parent process.        parent pid = 18552        parent ppid = 12596in child process.        child pid = 18553        child ppid = 18552        main2 pid = 18554        main2 ppid = 18553argc = 1 argv[0]=/home/xa00087/temp/test/main/main2 this is in main2 progress! this is in main2 progress! this is in main2 progress! this is in main2 progress! this is in main2 progress! main2 progress exit! child process exitWIFEXITED( status ) = 1WEXITSTATUS( status ) = 0parent process exit

可以看到 system也同样可以运行到main2, 但是运行结束之后还会继续执行当前子进程中的code, 而execl是直接把当前fork出来的子进程给完全替换掉了。

实际上system()函数有三个操作:

1. fork一个新的子进程

2. 在子进程中调用execl()... 

3. 在父进程中调用waitpid等待子进程的结束, 即执行command返回。

system的返回值很复杂, 介绍system如何使用的深度好文:

http://blog.sina.com.cn/s/blog_8043547601017qk0.html


 

0 0
原创粉丝点击