[英]Why the program didn't execute some sentences in this C programming or unix programming(execvp() System calls)?
[英]Why the program didn't execute some sentences in this C programming or unix programming(execvp() System calls)?
我有以下程序,当我运行该程序时,我真的很困惑为什么我的程序没有执行
int num=i;
printf("it is No.%d !",num);
printf("hello , I will excute execvp!");
我的程序基本上创建6个子进程来执行executebode()函数,然后使用execvp重载原始程序。 但是,每次运行程序时,字符串“ hello,我将执行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()函数吗? 我刚刚开始学习操作系统,所以我对此感到很困惑! 感谢你们对我的帮助!
正如user3629249所说,您有些困惑。 您会得到很多孩子的孩子……而wait(NULL)是无用的:)。
我使用这种结构来达到我的OS主题练习中的目标。
#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不同,则此过程为父进程。 在另一种情况下,该进程是子进程,因此必须停止(这些进程不必派生)。 通过这种方式,您只能得到所需的货叉。
其余代码相同:Pid == 0是子进程,其他是父进程。 您可以在子进程块中调用executenode(int i)(请记住,pid == 0 !!!您有错误)。 我认为每个调用中的变量都应具有正确的值。
祝好运!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.