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) ;
すべての標準出力をファイル尖った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;
}

猫のdup.cを達成するための例|機能が含まgrepが、それは学習の価値があります

公開された349元の記事 ウォンの賞賛6 ビュー9600

おすすめ

転載: blog.csdn.net/qq_23929673/article/details/99709748