[英]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()函数吗? 我刚刚开始学习操作系统,所以我对此感到很困惑! 感谢你们对我的帮助!
您面临的问题是两种不同因素共同作用的结果:
1-正如注释中提到的tonysdg一样 ,execvp会忽略当前的进程映像,并引用以下内容 :
execve()不会成功返回,并且调用过程的文本,数据,bss和堆栈会被加载的程序覆盖。
( execvp()
是execve()
的前端 )
和
2 -stdout是缓冲的流,这意味着当找到换行符或刷新缓冲区时才进行实际打印。
(见更多关于这个在陆克文Zwolinski的答案在这里 )
因此,现在,让我们看一下这些事物是如何相互作用并产生问题的:在调用execvp()
之前,您的输出缓冲区已经包含了前两个printf的内容 ,但是由于没有换行符,因此屏幕上不会打印任何内容。
然后,将执行execvp()
并覆盖当前进程中的所有内容,这当然意味着丢失了“先前”输出缓冲区中的内容。
在这里,您可以找到许多解决此问题的方法,为完整起见,我建议您在最终的printf
添加\\n
:
...
printf("hello , I will excute execvp!\n");
...
然后您就可以开始:
$ ./soc
hello, I am process:4701
hello, I am process:4702
hello, I am process:4703
hello, I am process:4704
hello, I am process:4705
hello, I am process:4706
it is No.5 !hello , I will excute execvp!
Hello, World!
it is No.4 !hello , I will excute execvp!
Hello, World!
it is No.3 !hello , I will excute execvp!
Hello, World!
it is No.2 !hello , I will excute execvp!
Hello, World!
it is No.1 !hello , I will excute execvp!
Hello, World!
it is No.0 !hello , I will excute execvp!
Hello, World!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.