c - exec() 在这个程序中做了什么?它会停止运行吗?
问题描述
int main(void){
char *argv[3] = {"Command-line","-1", NULL};
int i;
int pid = fork();
if(pid == 0){
for(int i=0;i<2;i++){
execvp("ls", argv);
fork();
printf("%d\n",i);
}
printf("One\n");
}
printf("Two\n");
return 0;
}
execvp 在这个程序中做了什么?子进程在此 execvp 调用之后是否继续运行,还是在此停止并且只有父进程继续运行?
另一个问题是,所有的 exec 调用都做同样的事情,但参数不同吗?
解决方案
以下建议的代码:
- 干净地编译
- 执行所需的功能
- 正确处理错误
现在建议的代码:
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
char *args[] = { "ls", NULL };
int pid = fork();
switch(pid)
{
case 0:
execvp("ls", args);
perror( "execvp failed" );
exit( EXIT_FAILURE );
break;
case -1:
perror( "fork failed" );
exit( EXIT_FAILURE );
break;
default:
waitpid( pid, NULL, 0 );
break;
}
return 0;
}
输出的部分列表(当没有错误发生时)是:
...
untitled
untitled1.c
untitled1.o
untitled2
untitled2.c
untitled2.o
untitled.c
untitled.c~
untitled.html
untitled.mak
untitled.o
untitled.s
untitled.txt
...
推荐阅读
- laravel - 在 laravel 文件管理器中将文件和照片文件夹更改为一个存储文件夹
- postgresql - 无法在 Ubuntu 17.10 上使用 postgis 安装 postgres 9.3
- android - DateUtils.getRelativeTimeSpanString 返回时间差,但结果包括当前时间
- angular - Angular / Material / Datepicker - 找不到 DateAdapter 的提供者
- javascript - 提交后模态不隐藏
- python - 使用从值除以数据透视表向量获得的百分比值为现有 csv 创建新列?
- excel - 用于在 Google Drive 中填写表格的宏不发送任何信息
- java - java GUI中这些被阻止的部分是什么
- sql - VB - 将 linq 中的属性设置为 sql 到此实例
- ruby-on-rails - 定义嵌套资源的特定路由