进程控制
1.编写一个minishell
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<errno.h>
#include<string.h>
#include<ctype.h>
#include<sys/wait.h>
int main()
{
while(1){
printf("[wangwenqi@localhost]# ");
fflush(stdout);
char buf[1024]={0};
//一直等待标准输入
fgets(buf,1023,stdin);
buf[strlen(buf)-1]='\0';
printf("cmd:[%s]\n",buf);
//对输入进行解析,得到程序名称以及运行参数
int argc=0;
char *argv[32]={NULL};
char* ptr=buf;
while(*ptr!='\0')
{
if(!isspace(*ptr)){
argv[argc++]=ptr;
while(!isspace(*ptr)&&ptr!='\0'){ptr++;}
*ptr='\0';
}
ptr++;
}
argv[argc]=NULL;
int i;
for(i=0;i<argc;i++){
printf("[%s]\n",argv[i]);
}
//创建子进程
int pid=fork();
if(pid==0){execvp(argv[0],argv);
exit(0);}
//父进程等待子进程退出
waitpid(-1,NULL,0);
}
return 0;
}
- 封装fork/wait等操作, 编写函数 process_create(pid_t* pid, void* func, void* arg), func回调函数就是子进程执行的入口函数, arg是传递给func回调函数的参数.
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
void process_Create(pid_t*pid,void *func,void* arg)
{
execlp("test10.20","argv[0]","argv[1]",NULL);
}
void* func(void *arg)
{
printf("i ve got the arg=%d\n",&arg);
}
int main()
{
void* func();
void* arg;
pid_t ret =fork();
if(ret==0){
process_Create(&ret,func,arg);
}
waitpid(-1,NULL,0);
}
3.调研popen/system
system()
先来看一下system()函数的简单介绍:
#include
<stdlib.h>
int system(const char *command);
为了更好的理解system()函数返回值,需要了解其执行过程,实际上system()函数执行了三步操作:
1.fork一个子进程;
2.在子进程中调用exec函数去执行command;
3.在父进程中调用wait去等待子进程结束。
对于fork失败,system()函数返回-1。
如果exec执行成功,也即command顺利执行完毕,则返回command通过exit或return返回的值。
(注意,command顺利执行不代表执行成功,比如command:“rm debuglog.txt”,不管文件存不存在该command都顺利执行了)
如果exec执行失败,也即command没有顺利执行,比如被信号中断,或者command命令根本不存在,system()函数返回127.
如果command为NULL,则system()函数返回非0值,一般为1.
popen()
system()函数用起来很容易出错,返回值太多,而且返回值很容易跟command的返回值混淆。这里推荐使用popen()函数替代,关于popen()函数的简单使用也可以通过上面的链接查看。
popen()函数较于system()函数的优势在于使用简单,popen()函数只返回两个值:
成功返回子进程的status,使用WIFEXITED相关宏就可以取得command的返回结果;
失败返回-1,我们可以使用perro()函数或strerror()函数得到有用的错误信息。
这篇文章只涉及了system()函数的简单使用,还没有谈及SIGCHLD、SIGINT和SIGQUIT对system()函数的影响,事实上,之所以今天写这篇文章,是因为项目中因有人使用了system()函数而造成了很严重的事故。现像是system()函数执行时会产生一个错误:“No child processes”。
具体过程参照:system和popen函数的解析