利用工作之余为小伙伴写了份作业,关于进程间通信的。题目如下:
父进程从键盘上接受1000个数据,对其求和sum1,子进程对这1000个数平方和sum2,结果传给父进程,父进程将sum1+sum2后,打印结果。 要求:用大小为10的共享区传递1000个数据;子进程用消息机制将sum2传给父进程。 |
主要利用共享内存实现进程间通信,使用管道实现进程间竞争关系,FreeBSD下测试通过。代码如下:时间有限,有可能有些不足,希望高手给予指点。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/shm.h>
#include <signal.h> const int key = 0x12345678;
static int pfd1[], pfd2[]; #define SHM_LEN (10*1024)
#define VAL_NUM 5 int init_shm() {
int shmid = -; shmid = shmget((key_t)key, SHM_LEN, | IPC_CREAT);
if (shmid < ) {
printf("shmget failed!\n");
exit(-);
} return shmid;
} void cancel_shm(int shmid) {
if (shmctl(shmid, IPC_RMID, ) == -) {
printf("shmctl failed!\n");
exit(-);
}
printf("cancel_shm successfully!\n");
} void *shm_get(int shmid) {
void *mem = NULL; mem = shmat(shmid, , );
if (mem == (void *)-) {
printf("shmat failed!\n");
exit(-);
} return mem;
} int get_val(int *val, int num) {
int i;
for (i = ; i < num; i++) {
printf("please input a num:");
scanf("%d", val + i);
}
}
void show_val (int *val, int num) {
int i;
for (i = ; i < num; i++) {
printf("%d\t", *(val + i));
}
printf("\n");
} int add_val (int *val, int num) {
int result = ;
int i; for (i = ; i < num; i++) {
result += *(val + i);
} return result;
} int square_val (int *val, int num) {
int result = ;
int i, tmp; for (i = ; i < num; i++) {
tmp = *(val + i);
result += (tmp * tmp);
} return result;
} void TELL_WAIT (void) {
if (pipe(pfd1) < || pipe(pfd2) < ) {
printf("pipe error!\n");
exit(-);
}
} void TELL_PARENT (pid_t pid) {
if (write(pfd2[], "c", ) != ) {
printf("write error!\n");
exit(-);
}
} void WAIT_PARENT (void) {
char c; if (read(pfd1[], &c, ) != ) {
printf("read error!\n");
exit(-);
}
} void TELL_CHILD (pid_t pid) {
if (write(pfd1[], "p", ) != ) {
printf("write error!\n");
exit(-);
}
} void WAIT_CHILD (void) {
char c; if (read(pfd2[], &c, ) != ) {
printf("read error!\n");
exit(-);
}
} int main(int argc, char *argv[]) {
void *mem = NULL;
int shmid = -;
pid_t pid = -;
int val[VAL_NUM];
int result = ; shmid = init_shm(); TELL_WAIT();
if ((pid = fork()) < ) { //error
printf("fork error!\n");
exit(-);
} else if (pid == ) { //child
int result = ; WAIT_PARENT(); mem = shm_get(shmid); //get share memery memcpy(val, mem, sizeof(int) * VAL_NUM);
result = square_val(val, VAL_NUM); *(int *)((void *)mem + SHM_LEN - ) = result; TELL_PARENT(pid); exit();
} else { //parent
int child_result = ; mem = shm_get(shmid); //get share memery
get_val(val, VAL_NUM); //get user input
memcpy(mem, val, sizeof(int) * VAL_NUM); //copy user input to share memery TELL_CHILD(pid); result = add_val(val, VAL_NUM); WAIT_CHILD();
child_result = *(int *)((void *)mem + SHM_LEN - );
printf("result:%d, child_result:%d, all:%d\n", result, child_result, result + child_result);
} cancel_shm(shmid); return ;
}