linux C 中调用新的进程 (system和execv)

本文探讨了在Linux C编程中如何使用`system`和`execv`函数创建新进程。实验涵盖了不同的场景,如`fork`后`execv`执行新进程而不影响原进程,`execv`执行成功后不返回,以及`system`调用的返回行为。测试用例包括了对进程执行流程和执行效果的详细说明。

test1:

#include <stdio.h>
#include <stdlib.h>
int main(void)
{
    printf("this is in the new process...\n");
    sleep(5);
    printf("I have sleep 5 seconds...\n");
}

test2:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void f(void)
{
   printf("After exec the new process...\n");
}
int main(void)
{
   if(fork()==0)
   {
        execv("./test1",NULL);
   }
   f();
}
test3:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void f(void)
{
   printf("After exec the new process...\n");
}
int main(void)
{ 
	if(fork()==0) 
	{ 
		if(execv("./test1",NULL)<0) 
			f(); 
	}
}


test4:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void f(void)
{
   printf("After exec the new process...\n");
}
int main(void)
{
	system("./test1"); 
	f();
}

test5:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void f(void)
{
   printf("After exec the new process...\n");
}
int main(void)
{
   system("./test1 &");
   f();
}
test2运行结果:

this is in the new process...

After exec the new process...

I have sleep 5 seconds...

test3运行结果:

this is in the new process...

I have sleep 5 seconds...

test4运行结果:

this is in the new process...

I have sleep 5 seconds...

After exec the new process...

test5运行结果:

this is in the new process...

After exec the new process...

I have sleep 5 seconds...


test2:fork出新进程后执行execv执行新的进程,不影响原进程,如果不fork,那么新的进程会取代原进程

test3:execv执行成功后不返回,所以f()执行不到

test4:通过系统调用的方式,test1执行完成后system才有返回值,然后继续执行

test5:后台调用,直接返回,执行结果也test2相同





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值