要求:
写2个程序,
程序a负责在内存里找bash,并把找到的bash,的PID转成int型的数据,到送给另一个进程,
程序b,接收数据,把这个PID关闭掉
数据传输用 消息队列
程序A:
程序1:mesg.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include"common.h"
int main(void)
{
/* 自定义消息结构体*/
struct mymsgbuf qbuf;
int msgqueue_id = mes_get();
pid_t pid;
char buf[100];
while(1)
{
/* 找bash的pid */
pid = findPid("bash");
/* */
sprintf(buf,"%d",pid);
printf("pid=%d\n",pid);
/*发送pid*/
send_message(msgqueue_id, &qbuf, 1, buf);
/*是0代表没找到bash*/
if(pid == 0)break;
sleep(1);
}
return EXIT_SUCCESS;
}
程序2:common.c
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/msg.h>
#include<string.h>
#include"mes.h"
int mes_get()
{
key_t key;
int msgqueue_id;
key = ftok("/root", 'm');
if (-1 == (msgqueue_id = msgget(key, IPC_CREAT | 0660)))
{
perror("msgget");
exit(1);
}
return msgqueue_id;
}
void read_message(int qid, struct mymsgbuf *qbuf, long type)
{
printf("Reading a message ...\n");
qbuf->mtype = type;
msgrcv(qid, (struct msgbuf*) qbuf, MAX_SEND_SIZE, type, 0);
}
void send_message(int qid, struct mymsgbuf *qbuf, long type, char* text)
{
printf("Sending a message ... \n");
qbuf->mtype = type;
strcpy(qbuf->mtext,text);
if (-1 == (msgsnd(qid, (struct msgbuf*)qbuf, strlen(qbuf->mtext)+1, 0)))
{
printf("gnhd\n");
perror("msgsnd");
exit(1);
}
}
void remove_queue(int qid)
{
msgctl(qid, IPC_RMID, 0);
}
int findPid(char *name)
{
char buf[100];
sprintf(buf, "ps -A | grep %s", name); //根据文件名找运行的pid
FILE *fp = popen(buf, "r");
if (fgets(buf, sizeof(buf), fp) != NULL)
{
pclose(fp);
return atoi(buf); /* 找到则返回PID*/
}
pclose(fp);
return 0; /* 如果找不到,则返回0*/
}
程序3:common.h
#ifndef MES_H_
#define MES_H_
#define MAX_SEND_SIZE 80
struct mymsgbuf
{
long mtype;
char mtext[100];
};
int mes_get();
void send_message(int qid,struct mymsgbuf *qbuf,long type,char* text);
void read_message(int qid,struct mymsgbuf *qbuf,long type);
void remove_queue(int qid);
int findPid(char *name);
#endif /* MES_H_ */
程序B:killbash.c
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include "common.h"
#include <unistd.h>
int main(void)
{
/* 创建消息队列*/
int msgqueue_id = mesg_get();
struct mymsgbuf qbuf;
pid_t pid;
while (1)
{
/* 读消息 */
read_message(msgqueue_id, &qbuf, 0);
pid = atoi(qbuf.mtext);
/* 打印PID*/
printf("pid=%d\n", pid);
if (pid == 0)
{
break;
}
/* 根据pid关bash*/
kill(pid, SIGKILL);
sleep(1);
}
/* 删除消息队列*/
remove_queue(msgqueue_id);
return EXIT_SUCCESS;
}
效果:先运行killbash.c ,消息队列没有东西,运行诸塞,然后运行mesg.c发送bash的pid,killbash.c读消息,关闭bash。
存在问题:发送的pid除0外,pid的数量还是多余打开的bash数量,而且killbash 要运行到第二次才能读到pid为0的。
why?