linuxC多进程通讯---无名管道dup

文章目录

举例1

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

int main1 (void)
{
	int fd, new_fd;
	fd = open ("write.txt", O_RDWR | O_CREAT, 0644);
	if (fd == -1)
	{
		perror ("open");
		exit (EXIT_FAILURE);
	}
	new_fd = dup (fd);
    printf ("fd = %d\nnew_fd = %d\n", fd, new_fd);
	write (fd, "hello", strlen("hello"));
	close (fd);
	write (new_fd, "world", strlen("world"));
	close (new_fd);
	return 0;
}

int main (void)
{
	int new_fd;
	new_fd = dup (1);
	write (1, "hello", strlen("hello"));
	write (new_fd, "world\n", strlen("world\n"));
	close (new_fd);
	return 0;
}

new_fd = dup (fd);
给new_fd分配一个新的文件描述符,使其和fd指向的文件一致,以后使用new_fd或fd均可
new_fd = dup (1);
使new_fd指向标准输出

举例2

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

#define handler_error(msg) \
    {perror(msg);exit(EXIT_FAILURE);}

int main (void)
{
    int fd, new_fd;
    char *buf = "hello world\n";

    fd = open ("data.log", O_RDWR | O_CREAT, 0644);
    if (fd == -1)
        handler_error("open");

    new_fd = dup2 (fd, 1);
    if (new_fd == -1)
        handler_error("dup2");

    printf ("fd: %d\n new_fd: %d\n", fd, new_fd);
    write (1, buf, strlen(buf));
    close (fd);

return 0;
}

new_fd = dup2 (fd, 1);
给标准输出1赋值为文件描述符fd,以后标准输出全部重定向到fd指向的文件中,返回值为赋予新含义的文件描述符,本例中返回1(这里1和fd指向同一文件)

举例3

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

int main (void)
{
	int pipe_fd[2];
	if (pipe (pipe_fd) == -1)
	{
		perror ("pipe");
		exit (EXIT_FAILURE);
	}
	else
	{
		int ret_from_fork;
		ret_from_fork = fork ();
		if (ret_from_fork == 0)  // child process
		{
		//	close (1);
			dup2 (pipe_fd[1], 1);
			execlp ("cat", "cat", "dup.c", NULL);
		}
		else
		{
		//	close (0);
			dup2 (pipe_fd[0], 0);
			close (pipe_fd[1]);
			execlp ("grep", "grep", "include", NULL);
		}
	}
	return 0;
}

该例实现了一个cat dup.c|grep include功能,很值得借鉴

linuxC多进程通讯---无名管道duplinuxC多进程通讯---无名管道dup 学无止境966 发布了349 篇原创文章 · 获赞 6 · 访问量 9628 私信 关注
上一篇:顺序表——顺序存储结构


下一篇:【排序】堆排序