下面是一个使用fork 并运行另外一个程序的例子:
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);
printf( "in child process.\n" );
printf("\tchild pid = %d\n",getpid());
printf("\tchild ppid = %d\n",getppid());
execl( "/home/xa000xx/temp/test/main/main2", "main2", ( char * )NULL );
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());
sleep(10);
printf("parent process exit\n");
}
exit(EXIT_SUCCESS);
}
main2的code:
void main( void )
{
char mine[128];
int i= 5;
while (i-- >0) {
sleep(1);
printf("this is in main2 progress! \n");
}
printf("main2 progress exit! \n");
}
执行结果如下:
~/temp/test/main$ ./main1
in parent process.
parent pid = 30987
parent ppid = 12596
in child process.
child pid = 30988
child ppid = 30987
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!
parent process exit
<a target=_blank href="mailto:xa000xx@xalnx6:~/temp/test/main$">xa000<span style="color:#000000;">xx</span>@xalnx6:~/temp/test/main$</a>
如何向main2传递参数呢?
修改下main1 部分code如下:
int errno = execl( "/home/xa00087/temp/test/main/main2", "main2", "test1", "test2", "test3",( char * )NULL );
printf( "execl failed, error code: %d(%s)", errno, strerror( errno ) );
printf("child process exit\n");
exit(EXIT_SUCCESS);
修改main2 如下:
void main(int argc,char *argv[])
{
int i = 0;
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 = 27782
parent ppid = 12596
in child process.
child pid = 27783
child ppid = 27782
main2 pid = 27783
main2 ppid = 27782
argc = 4
argv[0]=main2
argv[1]=test1
argv[2]=test2
argv[3]=test3
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!
parent process exit
exec用被执行的程序完全替换了调用进程的映像。Fork创建了一个新进程就产生了一个新的PID,exec启动一个新程序,替换原有进程。因此被执行的进程的PID不会改变。exec只是用另一个新程序替换了当前进程的正文、数据、堆和栈段。
可以看到child process exit 并没有打印出来, 说明进程已经转到main2了, 在mian2中退出的。
main1中传入的参数再main2中会被打印出来。