多进程学习2

多进程学习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 = 12596
in child process.
        child pid = 18553
        child ppid = 18552
        main2 pid = 18554
        main2 ppid = 18553
argc = 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 exit
WIFEXITED( status ) = 1
WEXITSTATUS( status ) = 0
parent 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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值