红联Linux门户
Linux帮助

dup2 如何使用

发布时间:2008-05-04 13:01:36来源:红联作者:fangshenghao
请问一下 dup2 如何使用的, 查了好多资料, 始终不明白参数是如何传递的.
我想要把下面的程序通过dup2来实现, 能不能帮我看一下

[table=95%][tr][td][font=FixedSys][color=#FF9900]/*------------------------*/
/* pipe3.c*/

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>

int main()
{
    int data_processed;
    int file_pipes[2];
    const char some_data[]="123";
    char buffer[BUFSIZ+1];
    pid_t fork_result;
    
    memset(buffer, '\0', sizeof(buffer));

    if(pipe(file_pipes) == 0)
    {
        fork_result = fork();
        if(fork_result == -1)
        {
            fprintf(stderr, "Fork failure");
            exit(EXIT_FAILURE);
        }
        if(fork_result == 0)
        {
            sprintf(buffer, "%d", file_pipes[0]);
            (void)execl("pipe4","pipe4", buffer, (char*)0);
            exit(EXIT_FAILURE);
        }
        else
        {
            data_processed = write(file_pipes[1], some_data, strlen(some_data));
            printf("%d - wrote %d bytes\n", (int)getpid(), data_processed);
        }
    }

    exit(EXIT_SUCCESS);
}
[/color][/font][/td][/tr][/table]
[table=95%][tr][td][font=FixedSys][color=#FF9900]/* pipe4 */

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

int main(int argc, char *argv[])
{
    int data_processed;
    
    char buffer[BUFSIZ +1];
    int file_descriptor;

    memset(buffer, '\0', sizeof(buffer));
    sscanf(argv[1], "%d", &file_descriptor);
    data_processed = read(file_descriptor, buffer, BUFSIZ);

    printf("%d - read %d bytes: %s\n", getpid(), data_processed, buffer);

    exit(EXIT_SUCCESS);
}
[/color][/font][/td][/tr][/table]

输出:
$ ./pipe3
980 - wrote 3 bytes
981 - read 3 bytes: 123

程序pipe3中调用pipe4, 我想知道如果用 dup2来实现是怎么改的.
文章评论

共有 1 条评论

  1. 黄富强 于 2008-05-04 14:28:45发表:

    理解dup和dup2
    http://read.newbooks.com.cn/info/50266.html