概述
管道和进程的创建
(1)管道的创建
#include<stdlib.h>
#include<sys/stat.h>
#include<string.h>
#include<errno.h>
int main()(int argc,char **argv)
if(argc<2)
{
fprintf(stdout,"Usage:%s<filename>n",argv[0];
exit(1);
}
//int mkfifo(const char *path,mode_t mode);
if(mkfifo(argv[1],0644)<0)
{
fprintf(stderr,"mkfifo() failed:%sn",strerror(errno));
exit(1);
}
return 0;
}
这几行代码可以创建一个管道
**(2)写进程的创建**
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<string.h>
#include<errno.h>
int main(int argc,char *argv[])
{
int fd;
char str[1024];
ssize_t n;
if(argc<2){
printf("Please input 'fifo name' after %sn",argv[0];
exit(1);
}
mkfifo(argv[1],0644);
if((fd=open(argv[1],O_WRONLY))<0){
printf("Opening Write_fifo Failed.n");
exit(1);
}
printf("Write_fifo is ready.n");
printf("Waitting message....nn");
while(1){
printf("Please input:n");
fgets(str,sizeof(str),stdin);
write(fd,dtr,strlrn(str)+1);
if(!strcmp(str,":qn")){
printf("Write_fifo closed.n");
break;
}
}
close(fd);
return 0;
}
此为写进程的创建。
(3)读进程的创建。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
int search(char *str1, char *str2);
int count = 0;
int main(int argc, char *argv[])
{
int fd1, fd2;
char str1[1024], str2[1024];
ssize_t n;
if (argc < 2) {
printf("Please input 'fifo name' after %sn", argv[0]);
exit(1);
}
if ((fd1 = open(argv[1], O_RDONLY)) < 0) {
printf("Opening Read_fifo failed.n");
exit(1);
}
if ((fd2 = open("./target.txt", O_RDONLY)) < 0) {
printf("Opening Search_file failed.n");
exit(1);
}
lseek(fd2, 0, SEEK_SET);
printf("Write_fifo is ready.n");
printf("Waiting message......nn");
while (read(fd1, str1, sizeof(str1)) > 0) {
if (!strcmp(str1, ":qn")) {
printf("Read_fifo closed.n");
break;
}
str1[strlen(str1) - 1] = '