day8_IOj进程线程
1、使用消息队列实现多进程的数据互相传输
1.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
#include <signal.h>
#include <sys/wait.h>
#include <sys/ipc.h>
#include <sys/msg.h>
// 队列中的数据结点
typedef struct msgbuf
{
long mtype; /* message type, must be > 0 */
char mtext[1024]; /* message data */
} stringbuf;
#define SIZE sizeof(stringbuf) - sizeof(long)
int main(int argc, const char *argv[])
{
// 获取Key值 根据根目录 和 数字1
key_t key;
if ((key = ftok("/", 1)) == -1)
{
perror("ftok");
return -1;
}
// 创建消息队列
int msgid;
if ((msgid = msgget(key, IPC_CREAT | 0666)) == -1)
{
perror("ftok");
return -1;
}
pid_t pid = fork();
if (pid == -1)
{
perror("fork");
return -1;
}
else if (pid == 0)
{
/* son */
stringbuf buf;
while (1)
{
if (msgrcv(msgid, &buf, SIZE, 8, 0) == -1)
{
perror("msgsnd");
return -1;
}
if (strcmp(buf.mtext, "quit") == 0)
{
break;
}
printf("A:message come... %s\n", buf.mtext);
}
msgctl(msgid, IPC_RMID, NULL);
kill(getppid(), SIGKILL);
exit(EXIT_SUCCESS);
}
else
{
/* father */
stringbuf buf = {.mtype = 6};
while (1)
{
fgets(buf.mtext, sizeof(buf.mtext), stdin);
buf.mtext[strlen(buf.mtext) - 1] = '\0';
printf("A:我要发送的数据: \n");
if (msgsnd(msgid, &buf, SIZE, 0) == -1)
{
perror("msgsnd");
return -1;
}
if (strcmp(buf.mtext, "quit") == 0)
{
break;
}
}
kill(pid, SIGKILL);
}
return 0;
}
2.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
#include <signal.h>
#include <sys/wait.h>
#include <sys/ipc.h>
#include <sys/msg.h>
// 队列中的数据结点
typedef struct msgbuf
{
long mtype; /* message type, must be > 0 */
char mtext[1024]; /* message data */
} stringbuf;
#define SIZE sizeof(stringbuf) - sizeof(long)
int main(int argc, const char *argv[])
{
// 获取Key值 根据根目录 和 数字1
key_t key;
if ((key = ftok("/", 1)) == -1)
{
perror("ftok");
return -1;
}
// 创建消息队列
int msgid;
if ((msgid = msgget(key, IPC_CREAT | 0666)) == -1)
{
perror("ftok");
return -1;
}
pid_t pid = fork();
if (pid == -1)
{
perror("fork");
return -1;
}
else if (pid == 0)
{
/* son */
stringbuf buf = {.mtype = 8};
while (1)
{
fgets(buf.mtext, sizeof(buf.mtext), stdin);
buf.mtext[strlen(buf.mtext) - 1] = '\0';
printf("B:我要发送的数据: \n");
if (msgsnd(msgid, &buf, SIZE, 0) == -1)
{
perror("msgsnd");
return -1;
}
if (strcmp(buf.mtext, "quit") == 0)
{
break;
}
}
exit(EXIT_SUCCESS);
}
else
{
/* father */
stringbuf buf;
while (1)
{
if (msgrcv(msgid, &buf, SIZE, 6, 0) == -1)
{
perror("msgsnd");
return -1;
}
if (strcmp(buf.mtext, "quit") == 0)
{
break;
}
printf("B:message come... %s\n", buf.mtext);
}
msgctl(msgid, IPC_RMID, NULL);
kill(getppid(), SIGKILL);
exit(EXIT_SUCCESS);
}
return 0;
}