欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

信息量编程

程序员文章站 2024-03-19 18:39:52
...

1.#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

   //int semget(key_t key, int nsems, int semflg);
    //int semctl(int semid, int semnum, int cmd, ...);
     union semun {
           int              val;    /* Value for SETVAL */
           struct semid_ds *buf;    /* Buffer for IPC_STAT, IPC_SET */
           unsigned short  *array;  /* Array for GETALL, SETALL */
           struct seminfo  *__buf;  /* Buffer for IPC_INFO
                                       (Linux-specific) */
       };

int main()
{
key_t key;
int semid;

    key = ftok(".",1);
    semid = semget(key,1,IPC_CREAT|0666);
    union semun initsem;
    initsem.val = 1;
    semctl(semid,0,SETVAL,initsem);//

    int pid = fork();
    if(pid>0) {
            printf("this is father\n");
    } else if(pid == 0) {
            printf("this is child\n");
    } else {
            printf("fork error\n");
    }
    return 0;

}
2.终极信号量编程
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

   //int semget(key_t key, int nsems, int semflg);
   //int semop(int semid, struct sembuf *sops, size_t nsops);

    //int semctl(int semid, int semnum, int cmd, ...);
     union semun {
           int              val;    /* Value for SETVAL */
           struct semid_ds *buf;    /* Buffer for IPC_STAT, IPC_SET */
           unsigned short  *array;  /* Array for GETALL, SETALL */
           struct seminfo  *__buf;  /* Buffer for IPC_INFO
                                       (Linux-specific) */
       };

void pGetkey(int id)
{
struct sembuf set;
set.sem_num = 0;
set.sem_op = -1;
set.sem_flg = SEM_UNDO;
semop(id,&set,1);
printf(“getkey\n”);
}

void vPutBackkey(int id)
{
struct sembuf set;
set.sem_num = 0;
set.sem_op = 1;
set.sem_flg = SEM_UNDO;
semop(id,&set,1);
printf(“putbackkey\n”);
}
int main()
{
key_t key;
int semid;

    key = ftok(".",1);
    semid = semget(key,1,IPC_CREAT|0666);
    union semun initsem;
    initsem.val = 0;
    semctl(semid,0,SETVAL,initsem);//

    int pid = fork();
    if(pid>0) {
            pGetkey(semid);
            printf("this is father\n");
            vPutBackkey(semid);
            semctl(semid,0,IPC_RMID );    //销毁
    } else if(pid == 0) {
            printf("this is child\n");
             vPutBackkey(semid);
    } else {
            printf("fork error\n");

    }
    return 0;

}
信息量编程

相关标签: 多进程

上一篇: RUNOOB python练习题29

下一篇: