c - dup2() 和 exec()

标签 c exec parent-child pipe dup2

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>

int
main( int argc, char **argv)
{
    int pfds[ 2], i;
    size_t pbytrd;
    pid_t childpid;
    char buffer[ 200];

    pipe( pfds);
    if( ( childpid = fork() ) == -1)
    {
            perror( "fork error: ");
            exit( 1);
    }
    else if( childpid == 0)
    {
            close( pfds[ 0]);
            dup2( pfds[1], 1);
            close( pfds[ 1]);
            for( i = 0; i < 10; i++)
               printf("Hello...");
            execlp( "xterm","xterm","-e","./sample_a", (char *) 0);
            exit( 0);
}
else
{

        close( pfds[ 1]);
        for( ; ; )
        {
            if( ( pbytrd = read( pfds[ 0], buffer, sizeof( buffer) ) ) == -1)
            {
                perror(" read error: ");
                exit( 1);
            }
            else if( pbytrd == 0)
            {

                write( fileno( stdout), "Cannot read from pipe...\n", strlen( "Cannot read from pipe...\n") );
                exit( 0);
            }
            else
            {
                write( fileno( stdout), "MESSAGE: ", strlen( "MESSAGE: ") );
                write( fileno( stdout), buffer, pbytrd);
            }
        }       
}   
return( 0);

我的 sample_a.c 代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>

int
main( int argc, char **argv)
{
        int i;
        for( i= 0; i< 10; i++)
        write( fileno( stdout), "Hello...", strlen( "Hello...") );
    return( 0);
 }

在上面的代码中,我真正想做的是: 1) 将子进程的输出重定向到管道,并让父进程从管道中读取并将其打印到标准输出。

我能够将子进程输出(“printf”)从标准输出重定向到管道,但我无法将 execlp 的子进程 xterm 输出重定向到管道。

有人可以帮我吗?

最佳答案

xterm 是一个终端模拟器。它执行您提供的程序 (sample_a),将其输入和输出连接到自身,以便程序在其标准输入中接收用户输入,并向用户打印它发送到其标准的任何内容和错误输出。

您的程序正在做的是将 xterm 输出连接到管道,并尝试读取它。但是 xterm 是一个 GUI 程序,它通常不会向其输出写入数据。也许您并不清楚您到底想达到什么目的。

如果删除 xterm 部分,它应该会按预期工作,也就是说,父进程将看到 sample_a 写入输出的内容。

        execlp("./sample_a", "./sample_a", (char *) 0);

关于c - dup2() 和 exec(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4981113/

相关文章:

c - 如何通过 stdin 提供输入来使以下条件失败

C 文本文件到结构体、数组,然后输出

bash - 管道 docker run 容器 ID 到 docker exec

c - 如何在 amd64 中正确转储 IDT 条目?

c - 无法正确读取 .bmp 头文件

php - 使用 proc_open() 在 PHP 中运行 C 可执行文件

java - 安卓;使用执行("bugreport")

linux - 通过 fork : unexplainable behaviour 创建进程和子进程

java - 关闭子窗口时关闭父窗口

c - 使用 wait() 从子进程中检索返回码?