C 将fork()用于拆分进程-什么';这个节目有什么问题吗
我非常希望您能帮助我理解为什么在使用C 将fork()用于拆分进程-什么';这个节目有什么问题吗,c,linux,fork,C,Linux,Fork,我非常希望您能帮助我理解为什么在使用fork()命令后进程没有到达“子进程”。我正试图编写一个运行另一个程序的程序,但该程序似乎甚至没有到达子进程。我知道,既然“子进程”没有被打印到屏幕上,我真的很想知道为什么 这里是代码的草图-我甚至无法检查它是否正常,因为正如我所说,它甚至没有到达子进程,我总是得到“子错误退出” #包括 #包括 #包括 #包括 #包括 #包括 #包括 #包括 #包括 #包括 #包括 #包括 #包括 #包括 #包括 #包括 #包括 #定义maxargv5; int main(
fork()
命令后进程没有到达“子进程”。我正试图编写一个运行另一个程序的程序,但该程序似乎甚至没有到达子进程。我知道,既然“子进程”没有被打印到屏幕上,我真的很想知道为什么
这里是代码的草图-我甚至无法检查它是否正常,因为正如我所说,它甚至没有到达子进程,我总是得到“子错误退出”
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#定义maxargv5;
int main(){
char*cmd;
国际儿童基金会地位;
char*s;
字符**argv;
整数计数器;
cmd=(char*)calloc(5,sizeof(char)*20);
s=(char*)calloc(1,sizeof(char)*20);
argv=(char**)calloc(5,sizeof(char*)*20);
printf(“请编写命令”\n);
获取(cmd);
计数器=0;
while(strcmp(cmd,“exit”)!=0){
int-pid=fork();
如果(pid==0){
printf(“子过程”);
而(sscanf(cmd,“%s”,s)==1){
strcpy(argv[计数器],s);
计数器++;
}
execv(argv[0],argv);
printf(“该命令不合法”);
断言(0);
}
否则{
如果(等待(&child_状态)=-1){
printf(“等待pid的错误=%d\n”,pid);
出口(-1);
}
如果(已婚(子女身份)!=0)
printf(“子状态=%d\n”,WEXITSTATUS(子状态));
其他的
printf(“son因错误退出\n”);
}
printf(“请编写命令”);
获取(cmd);
}
免费的;
免费(cmd);
自由(argv);
printf(“这里也是”);
返回1;
}
printf(“子进程”)
,但这只是将字符串放在进程内的缓冲区中,并且由于您没有fflush()
它,因此它不会出现在屏幕上,并在exec
调用中与进程的其余内存一起丢弃。注意,stdout
通常是行缓冲的,所以如果有换行符,它会自动刷新。另外,默认情况下,stderr
是无缓冲的,更适合调试打印(fprintf(stderr,“子进程”)
)argv
中汇编从标准输入读取的命令,但它只有提供给您的实际参数的内存,因此您的内存溢出,并出现分段错误WIFEXITED
为零,则应使用WIFSIGNALED
和WTERMSIG
确认错误确实是SIGSEGVassert(0)
不是在出错后终止进程的好方法<代码>退出(1)已关闭。断言仅适用于指示代码本身存在错误的情况,如果这些情况发生,并且通常会从生产代码中消除(通过定义NDEBUG
)尝试
printf(“子进程\n”)代码>带有换行符。还添加对fflush(NULL)的调用
就在fork()
之前,您也可以将其称为子进程:)您正在“遭受缓冲”。另外,execv
需要程序的完整路径名,execvp
可能更容易。@mux+1获得出色的性别意识技能!:)
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <assert.h>
#include <signal.h>
#include <string.h>
#include <stdio.h>
#include <dirent.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/time.h>
#include <time.h>
#define MAXARGV 5;
int main() {
char* cmd;
int child_status;
char* s;
char** argv;
int counter;
cmd= (char*) calloc( 5, sizeof(char)*20);
s=(char*) calloc(1,sizeof(char)*20);
argv=(char**) calloc(5, sizeof(char*)*20);
printf("Please write a command\n");
gets(cmd);
counter = 0;
while (strcmp(cmd, "exit") != 0) {
int pid = fork();
if (pid == 0) {
printf("son process");
while (sscanf(cmd, "%s", s) == 1) {
strcpy(argv[counter], s);
counter++;
}
execv(argv[0], argv);
printf("the command is not legal");
assert(0);
}
else {
if (wait(&child_status) == -1) {
printf("error waiting for pid=%d\n", pid);
exit(-1);
}
if(WIFEXITED(child_status)!=0)
printf("son status=%d\n", WEXITSTATUS(child_status));
else
printf("son exited with error\n");
}
printf("Please write a command");
gets(cmd);
}
free(s);
free(cmd);
free(argv);
printf("here as well");
return 1;
}