无名
#include <myhead.h>int main(int argc, const char *argv[])
{int fd[2];if(pipe(fd)){perror("pipe error");return -1;}pid_t pid = fork();if(pid == 0){close(fd[0]);char buf[] = "hello world\n";while(1){write(fd[1], buf, sizeof(buf));sleep(1);}}else if(pid >0){close(fd[1]);char buf[32] = "";while(1){read(fd[0], buf, sizeof(buf));printf("%s", buf);}}else{perror("fork error");return -1;}return 0;
}
信号
#include <myhead.h>int main(int argc, const char *argv[])
{pid_t pid = fork();if(pid == 0){while(1){ puts("hello");sleep(1);}}else if(pid >0){sleep(5);kill(pid, SIGKILL);puts("over");}else{perror("fork error");return -1;}return 0;
}
消息队列
#include <myhead.h>typedef struct msgbuf{long mtype;char mtext[32];
}msg_t;int main(int argc, const char *argv[])
{key_t key = ftok("./", 'k');if(key == -1){perror("ftok error");return -1;}int msgid = msgget(key, IPC_CREAT|0664);if(msgid == -1){perror("msgget error");return -1;}msg_t msg = {1, "hello"};while(1){msgsnd(msgid, &msg, sizeof(msg), 0);sleep(1);}return 0;
}