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相同
本文探讨了在Linux C编程中如何使用`system`和`execv`函数创建新进程。实验涵盖了不同的场景,如`fork`后`execv`执行新进程而不影响原进程,`execv`执行成功后不返回,以及`system`调用的返回行为。测试用例包括了对进程执行流程和执行效果的详细说明。
&spm=1001.2101.3001.5002&articleId=6980771&d=1&t=3&u=0f03607858f444afb420193c66a42785)
1085

被折叠的 条评论
为什么被折叠?



