連考了兩週試,好久不見……
這次上機主題是“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
}
}
- 創建子進程並與父進程使用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)
{
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);
}
}
- 創建兩個子進程A和B。將A的標準輸出重定向到一個pipe的輸入端,將B的標準輸入定向到pipe的輸出端。兩個進程通過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)
{
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);
}
}
- 讓我們再亂一些。雙重重定向,兩個pipe。兩個子進程AB。將A的標準輸出重定向到pipe1的輸入端,標準輸入定向到pipe2的輸出端。將B的標準輸出重定向到pipe2的輸入端,標準輸入定向到pipe1的輸出端。兩個進程通過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)
{
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", O_CREAT | O_WRONLY);
//fprintf(fd, "Fils : receive b\n");
//write(tube[1], &a, 1);
exit(0);
} else {
//pere
dup2(tube[0], 0);
dup2(tube2[1], 1);
close(tube[0]);
close(tube2[1]);
//read( 0, &rcv, 1);
scanf("%c", &rcv);
fprintf(stderr, "perepereaaa\n");
//fd = fopen("pere.txt", O_CREAT | O_WRONLY);
// fd = fopen("pere.txt", "w");
// fprintf(fd, "receive a\n");
printf("b");
//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);
}
}
哦了,先貼到這,後半部分晚些時候再上。