日期:2014-05-16 浏览次数:20988 次
连考了两周试,好久不见……
这次上机主题是“pipe”,内容比较多,我分两次记录。
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
void main(int argc, char** argv)
{
	if(fork()==0) {
		//Section fils
		int fp = open("sortie", O_CREAT | O_WRONLY );
		if(fp == -1) {
			perror(0);
			exit(0);
		}
		printf("Avant la redirection\n");
		dup2(fp, 1);
		close(fp);
		printf("Après la redirection\n");
		execlp("echo", "echo", "I want to appear in the stdout, but...", NULL);
		exit(0);
	} else {
		//pere
	}
}
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
void main(int argc, char** argv)
{
	char a = 'a';
	char b = 'b';
	char rcv;
	int tube[2];
	pipe(tube);
	if(fork()==0) {
		//Section fils
		printf("Fils : write 'a' au tube.\n");
		write(tube[1], &a, 1);
		printf("Fils : Sleep 5 secondes avant l'écriture.\n");
		sleep(5);
		printf("Fils : write 'b' au tube.\n");
		write(tube[1], &b, 1);
		exit(0);
	} else {
		//pere
		read( tube[0], &rcv, 1);
		printf("Père : read du tube :%c. Lire le char suivant.\n", rcv);
		read( tube[0], &rcv, 1);
		printf("Père : read du tube :%c. \n", rcv);
	}
}
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
void main(int argc, char** argv)
{
	char a = 'a';
	char b = 'b';
	char rcv;
	int tube[2];
	pipe(tube);
	if(fork()==0) {
		//Section fils
		dup2(tube[1], 1);
		close(tube[1]);
		printf("a");
		//write(tube[1], &a, 1);
		exit(0);
	} else {
		//pere
		dup2(tube[0], 0);
		close(tube[0]);
		
		read( 0, &rcv, 1);
		//printf("Père : read du tube :%c. Lire le char suivant.\n", rcv);
		//read( tube[0], &rcv, 1);
		printf("Père : read du tube :%c. \n", rcv);
	}
}
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
void main(int argc, char** argv)
{
	char a = 'a';
	char b = 'b';
	char rcv;
	FILE* fd;
	int tube[2];
	int tube2[2];
	pipe(tube);
	pipe(tube2);
	if(fork()==0) {
		//Section fils
		dup2(tube[1], 1);
		dup2(tube2[0], 0);
		close(tube[1]);
		close(tube2[0]);
		printf("a");
		fflush(stdout);
		//read(0, &rcv, 1);
		scanf("%c",&rcv);
		fprintf(fdopen(2, "w"), "filsfilsbbb\n");
		//fd = fopen("fils.txt", "w");
		//fd = fopen("fils.txt"