在子进程中使用Scanf()通过execve执行无法正常工作

时间:2014-03-15 11:37:55

标签: c fork scanf execv

我正在执行一个非常简单的程序,它使用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中运行代码。谢谢

2 个答案:

答案 0 :(得分:2)

父进程完成后,控制权返回给shell;并且stdin可以关闭。

要保留孩子对stdin的访问权限,您可以让父母等到孩子完成。

所以,在你的父母:

else {
    printf("Parent process is terminating...\n");
    wait(NULL);
    return 0;
}

答案 1 :(得分:0)

您需要等待子进程完成,请修改您的代码

if(childpid == 0)
{
    execv("child",NULL);
    exit(1);
}
else
{
    wait(); //wait for child
    printf("Parent process is terminating...\n");
    return 0;
}