[英]Using Scanf() in child process executed via execv not working
I am executing a really simple program which takes input in integer from user using scanf. 我正在执行一个非常简单的程序,它使用scanf从用户获取整数输入。 I execute this program as a child program via fork() and execv.The child program never takes input from user.Any help would be appreciated.
我通过fork()和execv作为子程序执行该程序。子程序从不接受用户的输入。任何帮助将不胜感激。
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
pid_t childpid;
if((childpid = fork()) == -1)
{
perror("fork");
exit(1);
}
if(childpid == 0)
{
execv("child",NULL);
exit(1);
}
else
{
printf("Parent process is terminating...\n");
return 0;
}
}
and the child code is 而子代码是
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
int temp;
printf("This is Child Process. Child is going to sleep for 5 seconds\n");
sleep(5);
printf("Please enter an integer to terminate the process ");
scanf("%d",&temp);
printf("You entered %d ",temp);
printf("Child terminated");
return 0;
}
OUTPUT OUTPUT
[@localhost cascading]$ ./cascading
Parent process is terminating...
[@localhost cascading]$ This is Child Process. Child is going to sleep for 5 seconds
Please enter an integer to terminate the process You entered 12435[@localhost cascading]$ ^C
[@localhost cascading]$
I am running the code in fedora installed on a virtual machine.Thanks 我正在运行安装在虚拟机上的fedora中的代码。谢谢
Once the parent process finishes, control is returned to shell; 父进程完成后,控制权返回给shell; and
stdin
could be closed. 和
stdin
可以关闭。
To retain child's access to stdin
, you can let the parent wait until the child is done. 为了保留孩子对
stdin
的访问权限,你可以让父母等到孩子完成。
So, in your parent: 所以,在你的父母:
else {
printf("Parent process is terminating...\n");
wait(NULL);
return 0;
}
You need to wait for child process to be finished, please modify your code like this 您需要等待子进程完成,请修改您的代码
if(childpid == 0)
{
execv("child",NULL);
exit(1);
}
else
{
wait(); //wait for child
printf("Parent process is terminating...\n");
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.