gpt4 book ai didi

linux - 为什么程序没有执行这个C编程或unix编程中的某些语句(execvp()系统调用)?

转载 作者:行者123 更新时间:2023-11-30 17:10:35 25 4
gpt4 key购买 nike

我有以下程序,当我运行该程序时,我感到非常困惑,为什么我的程序没有执行

   int num=i;
printf("it is No.%d !",num);
printf("hello , I will excute execvp!");

我的程序基本上创建了6个子进程来执行executionbode()函数,然后使用execvp来重载原始程序。但是,每次运行程序时,字符串“你好,我将执行 execvp”永远不会出现!另外我认为上面这三句话也没有在运行的程序中执行?有人能告诉我为什么吗?这是我的程序

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include "makeargv.h"
#include "redirection.h"
#include <sys/wait.h>



int executionnode(int i);

int main(){
pid_t childpid;
int i;
int row=6;
for(i=0;i<row;i++)
{ childpid=fork();
if(childpid==0)
continue;
else if (childpid>0)
executionnode(i);

else {
perror("something wrong");
exit(1);
}
}


}


int executionnode(int i){
sleep(i);
printf("hello, I am process:%ld\n",(long)getpid());
wait(NULL);
char *execArgs[] = { "echo", "Hello, World!", NULL };
int num=i;
printf("it is No.%d !",num);
printf("hello , I will excute execvp!");
execvp("echo", execArgs);

}

有人能告诉我为什么吗?以及如何解决它?我感觉真的很奇怪吗?是因为 execvp() 函数吗?我刚开始学习操作系统,所以我真的很困惑!谢谢你帮助我!

最佳答案

正如用户3629249所说,你有些困惑。你会得到很多 child 的 child 的 child ......而 wait(NULL) 是没用的:)。

我使用这个结构来实现我的操作系统主题练习中的目标。

#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#define N 5

int main(int argc, char const *argv[])
{
pid_t pid,pids[N];
int i, num_pids = 0;
int state = 0;
int prior[]={1,3,5,2,4};

pid_t parent_pid = getpid();
printf("Parent pid is %i\n",father_pid);

// This for loop is the key
for (i = 0; i < N && getppid() != parent_pid; i++)
{
if ((pid = fork()) < 0)
{
printf ("fork error\n");
exit(-1);
}
pids[num_pids++] = pid;
}

if (pid == 0) // Child processes
{
printf("I am the child %i\n",getpid());
}
else // Parent process
{
for (i = 0; i < N; i++)
{
int pid_index = prior[i]-1; // Array starts with 0
pid = waitpid(pids[pid_index]);
printf("Children %i ended\n",pids[indice_pid]);
printf("%i alive children\n",N-1-i);
}
}

return 0;
}

这个结构之所以有效,是因为您将父进程的 pid 保存在parent_pid 变量中,并将每个进程的父进程 pid 与 getppid() 进行比较。如果此 pid 与parent_pid 不同,则此进程是父进程。在另一种情况下,该进程是一个子进程,因此它必须停止(这些进程不必 fork )。通过这种方式,您可以只获得您需要的 fork 。

其余代码相同:Pid==0 为子进程,其他为父进程。您可以在子进程 block 中调用executionnode(int i)(记住,pid==0!!!您有一个错误)。我认为 i 变量在每次调用中都应该具有正确的值。

祝你好运!

关于linux - 为什么程序没有执行这个C编程或unix编程中的某些语句(execvp()系统调用)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32813440/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com