1 程序間通信

1.1 概念
1.2 匿名管道-PIPE
基本概念
pipe()
管道建立流程
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
int main()
{
// create pipe
int fd[2]; // read-fd[0] write-fd[1]
int ret = pipe(fd);
if(ret < 0)
{
perror("pipe error\n");
return -1;
}
// create child process
pid_t pid = fork();
if(pid <0)
{
perror("fork error! \n");
return -1;
}
else if(pid > 0)
{
// farther_P close read-
close(fd[0]);
write(fd[1], "hello_xhh", sizeof("hello_xhh"));
wait(NULL);
}
else if(pid == 0)
{
// child_P close write-
close(fd[1]);
char buf[64];
memset(buf, 0x00, sizeof(buf));
int n = read(fd[0], buf, sizeof(buf));
printf("read over, n = [%d], buf = [%s]\n", n, buf);
}
return 0;
}
1.3 命名管道-FIFO
流程
demo
- write
// FIFO Write
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
int main()
{
// test file is exit ?
int ret = access("./xhhfifo", F_OK);
if(ret != 0)
{
// create mfifo file
int ret = mkfifo("./xhhfifo", 0777);
if(ret < 0)
{
perror("fifo error !\n");
return -1;
}
}
// open file
int fd = open("./xhhfifo", O_RDWR);
if(fd < 0)
{
perror("open error! \n");
return -1;
}
// write file
while(1)
{
write(fd, "xhh18", strlen("xhh18"));
sleep(1);
}
// close
sleep(60);
close(fd);
return 0;
}
- read
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
int main()
{
// create mfifo file
/*int ret = mkfifo("./xhhfifo", 0777);
if(ret < 0)
{
perror("fifo error !\n");
return -1;
}*/
// open file
int fd = open("./xhhfifo", O_RDWR);
if(fd < 0)
{
perror("open error! \n");
return -1;
}
// read
char buf[64];
memset(buf, 0x00, sizeof(buf));
while(1)
{
int n = read(fd, buf, sizeof(buf));
printf("read over, n = [%d], buf = [%s]\n", n, buf);
}
// close
close(fd);
return 0;
}
1.4 記憶體映射 mmap
2 程序與線程
2.1 守護程序——不依賴與終端
2.2 線程的概念
其餘視訊。。。