我正在执行一个非常简单的程序,它使用 scanf 从用户那里获取整数输入。我通过 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;
}
}
子代码是
#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;
}
输出
[@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]$
我在虚拟机上安装的 fedora 中运行代码。谢谢