Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/64.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用C为linux编写shell时,某个进程的exec是无限循环的_C_Linux_Shell_Exec_Fork - Fatal编程技术网

用C为linux编写shell时,某个进程的exec是无限循环的

用C为linux编写shell时,某个进程的exec是无限循环的,c,linux,shell,exec,fork,C,Linux,Shell,Exec,Fork,以下是相关的代码片段: if(!strcmp(args[0],"run")){ pid_t pid = fork(); if(pid == 0){ execvp(args[1], args); fprintf(stdout, "Process could not be found in this directory\n");

以下是相关的代码片段:

if(!strcmp(args[0],"run")){
                pid_t pid = fork();
                if(pid == 0){
                  execvp(args[1], args);
                  fprintf(stdout, "Process could not be found in this directory\n");
                  kill((int)getpid(), SIGKILL);
                }
                else{
                    if(pid < 0)
                        exit(1);

                    fprintf(stdout, "PID of Process = %d\n", pid);
                    int success = waitpid(pid, &childExitStatus, WUNTRACED | WCONTINUED);

                    if(success == -1)
                        exit(EXIT_FAILURE);
                }

            }
if(!strcmp(args[0],“run”)){
pid_t pid=fork();
如果(pid==0){
execvp(args[1],args);
fprintf(stdout,“在此目录中找不到进程\n”);
kill((int)getpid(),SIGKILL);
}
否则{
if(pid<0)
出口(1);
fprintf(标准输出,“进程的PID=%d\n”,PID);
int success=waitpid(pid,&childExitStatus,WUNTRACED | WCONTINUED);
如果(成功==-1)
退出(退出失败);
}
}

现在,当我运行Libre Office math之类的进程时,它只会打开它的一个实例。然而,当我尝试使用这段代码打开xterm时,它将继续一次又一次地执行,在我中断并退出之前创建了许多xterm实例。我没有看到任何循环会导致这种情况发生。了解这是为什么吗?

调用
execvp()
是不正确的,因为它在开始时传递了一个额外的参数“run”。以这种方式执行
xterm
时,效果类似于
xterm-xterm
,并使xterm使用
xterm
作为shell。新的xterm继承了一个
SHELL
环境变量,该变量会导致它启动另一个xterm,直到限制用尽为止。

除了jilles对当前问题的回答之外,您应该知道如果
execvp
失败调用
fprintf
是不明智的,因为它会导致重复先前缓冲的输出。这还意味着您不能安全地使用
vWork
,这仍然是一个有价值的优化(特别是当父进程使用大量内存时)

不幸的是,没有报告
exec
故障的好方法。我倾向于这样做

if (pid == 0) {
    execvp(...);
    /* if we got here, something bad happened */
    _exit(127);
}

也许你的虫子在别处。查看现有的自由软件外壳。尝试
execvp(args[1],args+1)
,可能xterm被第一个参数
run
而不是
xterm
@BasileStarynkevitch弄糊涂了。谢谢,我一定会看完我的全部代码。不过,这对我来说更像是一个练习,了解linux中进程的来龙去脉。非常感谢@rmartinjak,这解决了问题。这是解决方案,只需要将其传递到下一个地址即可。谢谢。谢谢,我会记住这一点,并修改我的代码