进程间通信(C/C++)
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
int main()
{
int fd[2];
int ret = pipe(fd);
if (ret < 0) {
perror("pipe error");
return -1;
}
pid_t pid = fork();
if (pid < 0) {
perror("fork error");
}
else if (pid > 0) {
close(fd[0]);
write(fd[1], "cp666", strlen("cp666"));
}
else {
close(fd[1]);
char buf[1024];
memset(buf, 0*00, sizeof(buf));
read(fd[0], buf, sizeof(buf));
printf("%s\n", buf);
}
return 0;
}
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <string.h>
#include <errno.h>
int main()
{
int fd = open("./cp", O_WRONLY);
if (fd < 0) {
perror("open error");
return -1;
}
int ret = write(fd, "cp666", strlen("cp666"));
if (ret < 0) {
perror("write error");
}
else {
printf("write success\n");
}
close(fd);
return 0;
}
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <string.h>
#include <errno.h>
int main()
{
int fd = open("./cp", O_RDONLY);
if (fd < 0) {
perror("open error");
return -1;
}
int ret = mkfifo("./cp", 0666);
if (ret < 0 && errno != EEXIST) {
perror("mkfifo error");
return -1;
}
char buf[1024];
memset(buf, 0*00, sizeof(buf));
int n = read(fd, buf, sizeof(buf));
if (n < 0) {
perror("read error");
}
else if (n == 0) {
printf("no data");
}
else {
printf("%s\n", buf);
}
close(fd);
return 0;
}
#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
int main()
{
int fd = open("./cp", O_RDWR);
if (fd < 0) {
perror("open error");
return -1;
}
int len = lseek(fd, 0, SEEK_END);
void* addr = mmap(NULL, len, PROT_WRITE|PROT_READ, MAP_SHARED, fd, 0);
memcpy(addr, "cp666", strlen("cp666"));
close(fd);
return 0;
};
#include <stdio.h>
#include <sys/mman.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
int main()
{
int fd = open("./cp", O_RDWR);
if (fd < 0) {
perror("open error");
return -1;
}
int len = lseek(fd, 0, SEEK_END);
void* addr = mmap(NULL, len, PROT_WRITE|PROT_READ, MAP_SHARED, fd, 0);
char* p = (char*)addr;
printf("%s", p);
close(fd);
return 0;
}
进程间的通信管道是一个读端一个写端,其中pipe用于有血缘的进程通信,mkfifo可用于无血缘的进程通信,表面上看是管道操作一个文件,一个去写一个去读,其实在读的过程要将文件从用户态进入内核态,再从内核态到用户态到文件,十分耗时。而共享内存是将文件直接映射到内核,内核到文件