Famous pipes
Errno is set only if a library function fails. When the function runs successfully, the value of errno is not modified. This means that we cannot determine if there is an error by testing the value of the errno. Conversely, it is only meaningful to check the value of errno when the called function hints that an error has occurred. Viewing error code errno is an important way to debug a program. When an exception occurs in a Linux C API function, the errno variable (include errno.h) is typically assigned an integer value, and different values represent different meanings, which can be inferred by looking at the value. In the actual programming with this trick to solve a lot of the original seemingly inexplicable problems. A well-known pipeline is more powerful than a nameless pipe, which allows communication between unrelated processes. A shell command can be used to create a well-known pipeline command format: mkfifo[option] nameoption option Mkfifo Create a name named pipe such as: Mkfifo fifo1 #建立一个fifo1的有名管道--p for pipe file cat & Lt Fifo1 #通过cat命令对管道进行读数据ls > Fifo1 #ls命令显示写入管道 Remove rm Delete named pipe function: unlink ();
Liezi:
Read the file
#include <sys/types.h>
2 #include <sys/stat.h>
3 #include <errno.h>
4 #include < Fcntl.h>
5 #include <stdio.h>
6 #include <string.h>
7 #include <stdlib.h>
8
9 #define FIFO "/tmp/myfifo"
10
One int main (int argc, CHAR**ARGV)
({
) char buf_r[100];
int FD;
Nread int;
if (Mkfifo (fifo,o_creat| O_EXCL) < 0) && (errno! = eexist))
+
printf ("Can ' t create fifoserver \ n");
printf ("Preparing for reading bytes. \ n ");
memset (Buf_r, 0,sizeof (buf_r));
Fd=open (fifo,o_rdonly| o_nonblock,0);
(FD = =-1)
, {
perror ("open");
+ exit (1);
+}
while (1)
29 {
memset (Buf_r, 0,sizeof (buf_r));
if (Nread=read (fd,buf_r, 100) = =-1)
32 {
if (Errno==eagain)
printf ("No data \ n");
35
36}
Notoginseng printf ("Read%sfrom fifo\n", buf_r);
Sleep (1);
39}
+ Pause ();
Unlink (FIFO);
42}
Write a file
1 #include <sys/types.h>
2 #include <sys/stat.h>
3 #include <errno.h>
4 #include <fcntl.h>
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <string.h>
8
9 #define Fifo_server "/tmp/myfifo"
10
one int main (int argc, char** argv)
12 {
int FD;
+ char w_buf[100]={'/'};
Nwrite int;
if (fd = =-1)
17 {
if (Errno==enxio)
printf ("Open error\n");
20}
Fd=open (fifo_server,o_wronly| o_nonblock,0);
if (argc = = 1)
printf ("Please send something\n");
strcpy (w_buf,argv[1]);
if (Nwrite = Write (fd,w_buf,100)) = =-1)
26 {
if (errno = = Eagain)
printf ("The FIFO has not been read yet\n");
29}
-Else
printf ("Write%s to the fifo\n", w_buf);
Linux interprocess communication--famous pipelines