本文整理汇总了C++中semget函数的典型用法代码示例。如果您正苦于以下问题:C++ semget函数的具体用法?C++ semget怎么用?C++ semget使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了semget函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: main
int main(int argc, char *argv[])
{
int ret, id, use_clone = T_NONE;
char *tsttype = NONESTR;
char buf[7];
if (argc != 2) {
tst_resm(TINFO, "Usage: %s <clone| unshare| none>", argv[0]);
tst_resm(TINFO, " where clone, unshare, or fork specifies"
" unshare method.\n");
tst_exit();
}
/* Using PIPE's to sync between container and Parent */
if (pipe(p1) == -1) { perror("pipe1"); tst_exit(); }
if (pipe(p2) == -1) { perror("pipe2"); tst_exit(); }
if (strcmp(argv[1], "clone") == 0) {
use_clone = T_CLONE;
tsttype = CLONESTR;
} else if (strcmp(argv[1], "unshare") == 0) {
use_clone = T_UNSHARE;
tsttype = UNSHARESTR;
}
tst_resm(TINFO, "Semaphore Namespaces Test : %s", tsttype);
/* Create 2 containers */
ret = do_clone_unshare_test(use_clone, CLONE_NEWIPC, check_sem1, NULL);
if (ret < 0) {
tst_resm(TFAIL, "clone/unshare failed\n");
tst_exit();
}
ret = do_clone_unshare_test(use_clone, CLONE_NEWIPC, check_sem2, NULL);
if (ret < 0) {
tst_resm(TFAIL, "clone/unshare failed\n");
tst_exit();
}
close(p2[1]);
read(p2[0], buf, 7);
if (strcmp(buf, "exists") == 0)
if (use_clone == T_NONE)
tst_resm(TPASS, "Plain cloned process able to access the semaphore "
"created\n");
else
tst_resm(TFAIL, "%s : In namespace2 found the semaphore "
"created in Namespace1\n", tsttype);
else
if (use_clone == T_NONE)
tst_resm(TFAIL, "Plain cloned process didn't find semaphore\n");
else
tst_resm(TPASS, "%s : In namespace2 unable to access the semaphore "
"created in Namespace1\n", tsttype);
/* Delete the semaphore */
id = semget(MY_KEY, 1, 0);
semctl(id, IPC_RMID, 0);
tst_exit();
return 0;
}
示例2: mysem_init
int mysem_init(mysem_t *sem, int pshared, unsigned int value){
if ((*sem = semget(IPC_PRIVATE, 1, PERMS)) == -1)
return -1;
return 0;
}
示例3: zbx_mutex_create_ext
/******************************************************************************
* *
* Function: zbx_mutex_create_ext *
* *
* Purpose: Create the mutex *
* *
* Parameters: mutex - handle of mutex *
* name - name of mutex (index for nix system) *
* forced - remove mutex if exists (only for nix) *
* *
* Return value: If the function succeeds, then return ZBX_MUTEX_OK, *
* ZBX_MUTEX_ERROR on an error *
* *
* Author: Eugene Grigorjev *
* *
* Comments: use alias 'zbx_mutex_create' and 'zbx_mutex_create_force' *
* *
******************************************************************************/
int zbx_mutex_create_ext(ZBX_MUTEX *mutex, ZBX_MUTEX_NAME name, unsigned char forced)
{
#ifdef _WINDOWS
if (NULL == (*mutex = CreateMutex(NULL, FALSE, name)))
{
zbx_error("error on mutex creating: %s", strerror_from_system(GetLastError()));
return ZBX_MUTEX_ERROR;
}
#else
#define ZBX_MAX_ATTEMPTS 10
int attempts = 0, i;
key_t sem_key;
union semun semopts;
struct semid_ds seminfo;
if (-1 == (sem_key = ftok(CONFIG_FILE, (int)'z')))
{
zbx_error("cannot create IPC key for path '%s', try to create for path '.': %s",
CONFIG_FILE, zbx_strerror(errno));
if (-1 == (sem_key = ftok(".", (int)'z')))
{
zbx_error("cannot create IPC key for path '.': %s", zbx_strerror(errno));
return ZBX_MUTEX_ERROR;
}
}
lbl_create:
if (-1 != ZBX_SEM_LIST_ID || -1 != (ZBX_SEM_LIST_ID = semget(sem_key, ZBX_MUTEX_COUNT, IPC_CREAT | IPC_EXCL | 0600 /* 0022 */)) )
{
/* set default semaphore value */
semopts.val = 1;
for (i = 0; ZBX_MUTEX_COUNT > i; i++)
{
if (-1 == semctl(ZBX_SEM_LIST_ID, i, SETVAL, semopts))
{
zbx_error("semaphore [%i] error in semctl(SETVAL): %s", name, zbx_strerror(errno));
return ZBX_MUTEX_ERROR;
}
zbx_mutex_lock(&i); /* call semop to update sem_otime */
zbx_mutex_unlock(&i); /* release semaphore */
}
}
else if (EEXIST == errno)
{
ZBX_SEM_LIST_ID = semget(sem_key, 0 /* get reference */, 0600 /* 0022 */);
if (1 == forced)
{
if (0 != semctl(ZBX_SEM_LIST_ID, 0, IPC_RMID, 0))
{
zbx_error("cannot recreate Zabbix semaphores for IPC key 0x%lx Semaphore ID %ld: %s",
sem_key, ZBX_SEM_LIST_ID, zbx_strerror(errno));
exit(EXIT_FAILURE);
}
/* semaphore is successfully removed */
ZBX_SEM_LIST_ID = -1;
if (ZBX_MAX_ATTEMPTS < ++attempts)
{
zbx_error("cannot recreate Zabbix semaphores for IPC key 0x%lx: too many attempts",
sem_key);
exit(EXIT_FAILURE);
}
if ((ZBX_MAX_ATTEMPTS / 2) < attempts)
zbx_sleep(1);
goto lbl_create;
}
semopts.buf = &seminfo;
/* wait for initialization */
for (i = 0; ZBX_MUTEX_MAX_TRIES > i; i++)
{
if (-1 == semctl(ZBX_SEM_LIST_ID, 0, IPC_STAT, semopts))
//.........这里部分代码省略.........
示例4: main
int main()
{
int i;
int prio_inheritance=0;
/************************************ Process 2 (Low Priority) **********************************/
int PID_L = getpid();
int PR_L = getpriority(PRIO_PROCESS,PID_L);
printf("The Priority of LOW Process %d = %d\n", PID_L,PR_L);
key_t key;
int shm_id;
char *shm, *s;
char c;
key = 5788; // name the shared memory
shm_id= shmget(key,100, IPC_EXCL | 0666); // make a shared memory of 27 bytes
if(shm_id < 0)
{
perror("shmget");
exit(1);
}
// Now attach the shared memory to our data space
if((shm = shmat(shm_id,NULL,0)) == (char *) -1)
{
perror("shmat");
exit(1);
}
sem_id = semget(key,1,0666 | IPC_CREAT);
if(!set_semvalue())
{
fprintf(stderr,"Failed to initiaalize the semaphore \n");
exit(EXIT_FAILURE);
}
/*
FILE *f = fopen("shared_mem_info.txt","r");
if (f == NULL)
{
printf("Error in opening file!!! \n");
exit(1);
}
fscanf(f,"%d",&shm_id);
fclose(f);
printf("shared memory id = %d \n",shm_id);
*/
printf("Address = %d\n",shm);
for(s=shm; *s !=NULL; s++)
{
putchar(*s);
}
putchar('\n');
union semun sem_union;
who_locked = semctl(sem_id,0,GETPID,sem_union);
if(who_locked > 0)
{
printf("The PID = %d has locked the Semaphore. . . \n",who_locked);
/* setpriority(PRIO_PROCESS,who_locked,PRIO_H);
prio_inheritance = 1;
printf("The PID = %d has inherited priority of High that is %d...\n",who_locked,PRIO_H);
sched_yield();*/
}
sem_lock();
printf("High process has acquired the lock\n");
*shm='*';
/*Low Priority Task tries to acquire to lock the semaphore*/
/* sem_lock();
printf("Low Priority Process locks semaphore\n");
for(i=0;i<50;i++)
printf("Low Prio task is running...\n");
sem_unlock();
printf("Low Priority task is completed...\n");
printf("Inheritance = %d \n",prio_inheritance);
prio_inheritance = 0;
printf("Inheritance = %d \n",prio_inheritance);
*/
return 0;
}
示例5: svipc_sem_init
//---------------------------------------------------------------
// svipc_sem_init
//---------------------------------------------------------------
int svipc_sem_init(key_t key, int numslots)
{
int i, status;
int sempoolid = -1;
Debug(5, "svipc_sem_init %x\n", key);
if (numslots > 0)
{
sempoolid =
semget(key, numslots,
IPC_CREAT | IPC_PRIVATE | IPC_EXCL | 0666);
if (sempoolid == -1)
{
perror("sempoolid semget failed");
return -1;
}
// all semaphores are locked at startup
union semun semctlops;
semctlops.val = 0;
// fixme - SETALL perf improvement
for (i = 0; i < numslots; i++)
{
status = semctl(sempoolid, i, SETVAL, semctlops);
if (status == -1)
{
perror("sempoolid semctl failed");
return -1;
}
}
}
else if (numslots == 0)
{
// reset all the semaphores at 0 (hack functionality)
sempoolid = semget(key, 0, 0666);
if (sempoolid == -1)
{
perror("sempoolid semget failed");
return -1;
}
// find out how many sem are in the pool
union semun semctlops;
struct semid_ds stat;
unsigned int i;
semctlops.buf = &stat;
status = semctl(sempoolid, 0, IPC_STAT, semctlops);
if (status == -1)
{
perror("semctl IPC_STAT failed");
return -1;
}
for (i = 0; i < stat.sem_nsems; i++)
{
semctlops.val = 0;
status = 0;
status |= semctl(sempoolid, i, SETVAL, semctlops);
}
if (status == -1)
{
perror("sempoolid semctl failed");
return -1;
}
}
else
{
// noop, print info
return svipc_sem_info(key, 1);
}
return 0;
}
示例6: run_processes
int
run_processes(const struct proc_spec *specs, uint16_t count)
{
const int SEMFLAG = IPC_CREAT | IPC_EXCL | 0600;
union semun sem_arg;
struct sembuf sem_op;
unsigned short sem_init[] = { 0, 0 };
pid_t *children = 0;
unsigned seed;
int semid = -1;
int status;
if (!(children = calloc(count, sizeof(pid_t)))) {
fprintf(stderr, "%s: out of memory\n", prog);
status = -1;
goto end;
}
/* create semaphore, serves as a barrier */
if ((semid = semget(IPC_PRIVATE, 1, SEMFLAG)) == -1) {
fprintf(stderr, "%s: semget failed: %s\n",
prog, strerror(errno));
status = -1;
goto end;
}
/* initialize semaphore values to 0 */
sem_arg.array = sem_init;
if (semctl(semid, 0, SETALL, sem_arg) == -1) {
fprintf(stderr, "%s: semctl(SETVAL) failed: %s\n",
prog, strerror(errno));
status = -1;
goto end;
}
/* all processes need to be seeded seperately, so this gets
* incremented in the loop */
seed = time(0);
/* start workers */
for (uint16_t i = 0; i < count; i++) {
pid_t pid = fork();
if (pid == -1) {
fprintf(stderr, "%s: fork failed: %s\n",
prog, strerror(errno));
status = -1;
goto end;
} else if (!pid) {
srand(seed);
if (worker_begin(specs + i, semid) == -1)
exit(1);
exit(0);
}
children[i] = pid;
seed++;
}
/* spin until all processes are waiting on the semaphore, or one
* process ends prematurely */
for (;;) {
pid_t pid;
int val;
if ((val = semctl(semid, 0, GETNCNT)) == -1) {
fprintf(stderr, "%s: semctl(GETNCNT) failed: %s\n",
prog, strerror(errno));
status = -1;
goto end;
}
if (val == count) break; /* ready */
if ((pid = waitpid(-1, 0, WNOHANG)) == -1) {
fprintf(stderr, "%s: waitpid failed: %s\n",
prog, strerror(errno));
status = -1;
goto end;
} else if (pid) {
fprintf(stderr, "%s: at least one process exited "
"prematurely\n", prog);
status = -1;
goto end;
}
sched_yield();
}
/* release the processes to start*/
sem_op.sem_num = 0;
sem_op.sem_op = count;
sem_op.sem_flg = 0;
if (semop(semid, &sem_op, 1) == -1) {
fprintf(stderr, "%s: failed to signal semaphore: %s\n",
prog, strerror(errno));
status = -1;
goto end;
}
/* spin until all processes are waiting on the semaphore, or one
* process ends prematurely */
//.........这里部分代码省略.........
示例7: ftok
key_t QSystemSemaphorePrivate::handle(QSystemSemaphore::AccessMode mode)
{
if (-1 != unix_key)
return unix_key;
if (key.isEmpty()) {
errorString = QCoreApplication::tr("%1: key is empty", "QSystemSemaphore").arg(QLatin1String("QSystemSemaphore::handle"));
error = QSystemSemaphore::KeyError;
return -1;
}
// ftok requires that an actual file exists somewhere
int built = QSharedMemoryPrivate::createUnixKeyFile(fileName);
if (-1 == built) {
errorString = QCoreApplication::tr("%1: unable to make key", "QSystemSemaphore").arg(QLatin1String("QSystemSemaphore::handle"));
error = QSystemSemaphore::KeyError;
return -1;
}
createdFile = (1 == built);
// Get the unix key for the created file
unix_key = ftok(QFile::encodeName(fileName).constData(), 'Q');
if (-1 == unix_key) {
errorString = QCoreApplication::tr("%1: ftok failed", "QSystemSemaphore").arg(QLatin1String("QSystemSemaphore::handle"));
error = QSystemSemaphore::KeyError;
return -1;
}
// Get semaphore
semaphore = semget(unix_key, 1, 0600 | IPC_CREAT | IPC_EXCL);
if (-1 == semaphore) {
if (errno == EEXIST)
semaphore = semget(unix_key, 1, 0600 | IPC_CREAT);
if (-1 == semaphore) {
setErrorString(QLatin1String("QSystemSemaphore::handle"));
cleanHandle();
return -1;
}
if (mode == QSystemSemaphore::Create) {
createdSemaphore = true;
createdFile = true;
}
} else {
createdSemaphore = true;
// Force cleanup of file, it is possible that it can be left over from a crash
createdFile = true;
}
// Created semaphore so initialize its value.
if (createdSemaphore && initialValue >= 0) {
qt_semun init_op;
init_op.val = initialValue;
if (-1 == semctl(semaphore, 0, SETVAL, init_op)) {
setErrorString(QLatin1String("QSystemSemaphore::handle"));
cleanHandle();
return -1;
}
}
return unix_key;
}
示例8: main
int main( int argc, char *argv[] )
{
//create a key
key_t key;
key = ftok( FILE_FOR_KEY, 0 );
if( key == -1 )
{
printf( "%s: can't create a key\n", argv[0] );
exit(-1);
}
// create shared memory
int shm_id;
shm_id = shmget( key , SHM_SIZE, IPC_CREAT | IPC_EXCL | 0777 );
if( shm_id == -1 )
{
if( errno != EEXIST )
{
printf( "%s: can't create shared memory\n", argv[0] );
exit(-1);
}
else
{
shm_id = shmget( key , SHM_SIZE, 0 );
if( shm_id == -1 )
{
printf( "%s; can't open shared memory\n", argv[0] );
exit(-1);
}
}
}
//attach shared memory
struct msg * shm_adr;
shm_adr = (struct msg *) shmat( shm_id, NULL, 0 );
if( shm_adr == (void *) -1 )
{
printf( "%s; can't attach shared memory\n", argv[0] );
exit(-1);
}
//create semaphores
int sem_id;
sem_id = semget( key , 4, IPC_CREAT | IPC_EXCL | 0777 );
if( sem_id == -1 )
{
if( errno != EEXIST )
{
printf( "%s: can't create semaphores\n", argv[0] );
exit(-1);
}
else
{
sem_id = semget( key , 4, 0 );
if( sem_id == -1 )
{
printf( "%s; can't open semaphores\n", argv[0] );
exit(-1);
}
}
}
//--------------------------------------------------------------
if( argc == 2 )
{
//sender
//open file
int fd;
fd = open( argv[1], O_RDONLY );
if( fd == -1 )
{
printf( "%s: can't open %s\n", argv[0], argv[1] );
exit(-1);
}
//copy from file fo shared memory
int read_amount, ret_val;
//if sender is already exist
//snd 0
sem_ops[0].sem_num = 0;
sem_ops[0].sem_op = 0;
sem_ops[0].sem_flg = IPC_NOWAIT;
//snd +1
sem_ops[1].sem_num = 0;
sem_ops[1].sem_op = 1;
sem_ops[1].sem_flg = SEM_UNDO;
//operations
ret_val = semop( sem_id, &sem_ops[0], 2 );
if( ( ret_val != 0 ) && ( errno == EAGAIN ) )
{
printf("%s: sender is already exist\n", argv[0] );
exit(-1);
}
//cr section 1 ->
//.........这里部分代码省略.........
示例9: new_share
Share *
new_share( key_t key, int segment_size, int flags ) {
Share *share;
Node *node;
int semid;
struct shmid_ds shmctl_arg;
SEMUN semun_arg;
again:
if ( ( semid = semget( key, 3, flags ) ) < 0 ) {
LOG1( "semget failed (%d)", errno );
return NULL;
}
/* It's possible for another process to obtain the semaphore, lock it, *
* and remove it from the system before we have a chance to lock it. *
* In this case (EINVAL) we just try to create it again. */
if ( GET_EX_LOCK( semid ) < 0 ) {
if ( errno == EINVAL ) {
goto again;
}
LOG1( "GET_EX_LOCK failed (%d)", errno );
return NULL;
}
/* XXX IS THIS THE RIGHT THING TO DO? */
if ( segment_size <= sizeof( Header ) ) {
segment_size = SHM_SEGMENT_SIZE;
}
Newxz( node, 1, Node );
if ( ( node->shmid = shmget( key, segment_size, flags ) ) < 0 ) {
LOG1( "shmget failed (%d)", errno );
return NULL;
}
if ( ( node->shmaddr =
( Header * ) shmat( node->shmid, ( char * ) 0,
0 ) ) == ( Header * ) - 1 ) {
LOG1( "shmat failed (%d)", errno );
return NULL;
}
node->next = NULL;
Newxz( share, 1, Share );
share->key = key;
share->next_key = key + 1;
share->flags = flags;
share->semid = semid;
share->lock = 0;
share->head = node;
share->tail = node;
/* is this a newly created segment? if so, initialize it */
if ( ( semun_arg.val =
semctl( share->semid, 0, GETVAL, semun_arg ) ) < 0 ) {
LOG1( "shmctl failed (%d)", errno );
return NULL;
}
if ( semun_arg.val == 0 ) {
semun_arg.val = 1;
if ( semctl( share->semid, 0, SETVAL, semun_arg ) < 0 ) {
LOG1( "shmctl failed (%d)", errno );
return NULL;
}
share->head->shmaddr->length = 0;
share->head->shmaddr->next_shmid = -1;
share->head->shmaddr->shm_state = 1;
share->head->shmaddr->version = 1;
}
share->shm_state = share->head->shmaddr->shm_state;
share->version = share->head->shmaddr->version;
/* determine the true length of the segment. this may disagree *
* with what the user requested, since shmget() calls will *
* succeed if the requested size <= the existing size */
if ( shmctl( share->head->shmid, IPC_STAT, &shmctl_arg ) < 0 ) {
LOG1( "shmctl failed (%d)", errno );
return NULL;
}
share->segment_size = shmctl_arg.shm_segsz;
share->data_size = share->segment_size - sizeof( Header );
if ( RM_EX_LOCK( semid ) < 0 ) {
LOG1( "RM_EX_LOCK failed (%d)", errno );
return NULL;
}
return share;
}
示例10: main
int
main(void) {
char buff[100];
channel = (void *)malloc(200);
/*---Establezco los canales de comunicacion---*/
getDefaultChannel(channel);
if ( connectToChannel(channel,CLIENT) < 0 ) {
printf("Server not available\n");
return 0;
}
itoa(buff,GET_CHANNEL);
sendPacket(buff,strlen(buff)+1, channel, CLIENT);
receivePacket(buff,MAX_SIZE, channel, CLIENT);
disconnectFromChannel(channel);
stringToChannel(buff, channel);
connectToChannel(channel,CLIENT);
/*---Abro el pipe de sincronismo entre padre e hijo---*/
if( pipe(syncPipe) == -1 ){
printf("Error al crear el pipe de sincronismo en el client.\n");
return 0;
}
/*---Abro el pipe de pasaje de argumentos para seniales---*/
if( pipe(signalPipe) == -1 ){
printf("Error al crear el pipe de args para seniales.\n");
return 0;
}
/*---Seteo el semaforo---*/
int semkey = getpid();
semun x;
x.val = 1;
int flags = IPC_CREAT | IPC_EXCL;
if ( ( semid = semget(semkey, 1, 0666 | flags )) == -1 ) {
printf("Error al crear semaforo: %d\n", semkey);
return -1;
}
if ( semctl(semid, 0, SETVAL, x) == -1 ) {
printf("Error al configurar semaforo\n");
return -1;
}
/*---Configuracion de manejo de seniales---*/
/* SIGUSR1 -> SHELL_SIGNAL */
/* SIGUSR2 -> DRAFT_SIGNAL */
struct sigaction draftSigAct;
draftSigAct.sa_handler = draftSignalHandler;
sigemptyset(&(draftSigAct.sa_mask));
draftSigAct.sa_flags = SA_NODEFER;
struct sigaction shellSigAct;
shellSigAct.sa_handler = shellSignalHandler;
sigemptyset(&(shellSigAct.sa_mask));
shellSigAct.sa_flags = SA_NODEFER;
sigaction( SIGUSR1, &shellSigAct, NULL);
sigaction( SIGUSR2, &draftSigAct, NULL);
static struct sigaction act3;
act3.sa_handler = catchSigPipe;
sigfillset(&(act3.sa_mask));
sigaction(SIGPIPE, &act3, NULL);
static struct sigaction act1;
static struct sigaction act2;
/*Convenimos a este proceso como programa de envio de datos*/
senderPid = getpid();
pid_t auxPid;
switch( auxPid = fork() ) {
case -1:
printf("Error al configurar el cliente.\n");
break;
case 0:
receiverPid = getpid();
close(syncPipe[0]);
close(signalPipe[0]);
receive();
break;
default:
act1.sa_handler = shutDown;
sigfillset(&(act1.sa_mask));
sigaction(SIGINT, &act1, NULL);
act2.sa_handler = shutDown;
sigfillset(&(act2.sa_mask));
sigaction(SIGTSTP, &act2, NULL);
receiverPid = auxPid;
close(signalPipe[1]);
close(syncPipe[1]);
raise(SIGUSR1);break;
}
return 0;
}
示例11: main
int main(int argc, char *argv[])
{
// 创建虚拟主存
int *buf = (int*)mmap(NULL, sizeof(int)*MAXSEM, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS, -1, 0);
int times = MAXSEM;
if (2 == argc)
times = atoi(argv[1]);
// 获得信号量的描述符
full_id = semget(IPC_PRIVATE, 3, IPC_CREAT|0666);
empty_id = semget(IPC_PRIVATE, 3, IPC_CREAT|0666);
mutx_id = semget(IPC_PRIVATE, 1, IPC_CREAT|0666);
// 初始化P,V操作;
arg.val = 0;
semctl(full_id, 0, SETVAL, arg);
semctl(full_id, 1, SETVAL, arg);
semctl(full_id, 2, SETVAL, arg);
arg.val = 1;
semctl(empty_id, 0, SETVAL, arg);
semctl(empty_id, 1, SETVAL, arg);
semctl(empty_id, 2, SETVAL, arg);
semctl(mutx_id, 0, SETVAL, arg);
p[0].sem_num = 0;
v[0].sem_num = 0;
p[1].sem_num = 1;
v[1].sem_num = 1;
p[2].sem_num = 2;
v[2].sem_num = 2;
p[0].sem_op = -1;
v[0].sem_op = 1;
p[1].sem_op = -1;
v[1].sem_op = 1;
p[2].sem_op = -1;
v[2].sem_op = 1;
p[0].sem_flg = v[0].sem_flg = SEM_UNDO;
p[1].sem_flg = v[1].sem_flg = SEM_UNDO;
p[2].sem_flg = v[2].sem_flg = SEM_UNDO;
P.sem_op = -1;
V.sem_op = 1;
P.sem_flg = V.sem_flg = SEM_UNDO;
P.sem_num = V.sem_num = 0;
// Init_sem();
// 消费者1进程
if (fork() == 0) {
int i, message;
printf("child 1 process(PID=%d) is running.\n", getpid());
for (i=0; i<times; i++) {
// 申请数据;
semop(full_id, &p[0], 1);
// 申请对缓冲区的互斥操作
semop(mutx_id, &P, 1);
message = buf[0];
buf[0] = 0;
printf("child 1 PID=%d) get message:%d.\n", getpid(), message);
// 释放对缓冲区的互斥操作
semop(mutx_id, &V, 1);
// 释放申请数据
semop(empty_id, &v[0], 1);
}
printf("child 1 process(PID=%d) is over.\n", getpid());
exit(0);
}
// 消费者2进程
if (fork() == 0) {
int i, message;
printf("child 2 process(PID=%d) is running.\n", getpid());
for (i=0; i<times; i++) {
// 申请数据
semop(full_id, &p[1], 1);
// 申请对缓冲区的互斥操作
semop(mutx_id, &P, 1);
message = buf[1];
buf[1] = 0;
printf("child 2 PID=%d) get message:%d.\n", getpid(), message);
// 释放对缓冲区的互斥操作
semop(mutx_id, &V, 1);
// 释放申请数据;
semop(empty_id, &v[1], 1);
}
printf("child 2 process(PID=%d) is over.\n", getpid());
exit(0);
}
// 消费者3进程
if (fork() == 0) {
int i, message;
printf("child 3 process(PID=%d) is running.\n", getpid());
for (i=0; i<times; i++) {
// 申请数据
semop(full_id, &p[2], 1);
//.........这里部分代码省略.........
示例12: ipc_systemv_sem
void ipc_systemv_sem()
{
int semid;
key_t key;
const unsigned int perms = S_IRUSR | S_IWUSR | S_IWGRP; // 읽기/쓰기 권한이 있어야 함.
struct semid_ds ds;
key = ftok(KEY_PATH, 1);
// 세마포어의 갯수가 1개인(0번) 세마포어 집합을 생성한다.
semid = semget(key, 1, IPC_CREAT | IPC_EXCL | perms);
/*
세마포어에 접근하는 프로세스 중 세마포어를 생성하는 프로세스는 1개이다.
나머지 프로세스는 여기서 EEXIST 에러를 리턴받고 else로 가서 이미 생성된 세마포어에 접근하게 됨.
*/
if(semid != -1) {
union semun arg;
struct sembuf sop;
// 0번 세마포어 값을 0으로 설정
arg.val = 0;
if(semctl(semid, 0, SETVAL, arg) == -1)
errExit("semctl()");
/*
sem_op = 0의 값으로 semop을 호출하는 것은 세마포어 값이 0이 될때까지 블록한다는 의미이다.
그런데 이미 세마포어의 값이 0으로 초기화되기 때문에 no-op에 해당한다.
하지만 semop 호출은 sem_optime(접근 시간)을 변경해서
뒤이어 실행되는 다른 프로세스가 세마포어가 초기화되었음을 알 수 있게 한다.
*/
sop.sem_num = 0; // 세마포어 번호 0에 대해서,
sop.sem_op = 0; // 세마포어 값은 이미 0이므로 아무 작업도 이루어지지 않는다.
sop.sem_flg = 0;
if(semop(semid, &sop, 1) == -1) {
errExit("semop()");
} // 이 때 sem_optime이 업데이트됨.
// 0번 세마포어 값을 2로 설정.
// 따라서 세마포어 값이 1, 2일 때 프로세스들은 '작업'으로 진입할 수 있다.
arg.val = 2;
if(semctl(semid, 0, SETVAL, arg) == -1)
errExit("semctl()");
}
// key에 해당하는 세마포어 식별자가 이미 생성되어 있는 경우,
else {
const int MAX_TRIES = 10;
int j;
union semun arg;
// 이미 열려진 세마포어 식별자를 얻어옴.
if((semid = semget(key, 1, perms)) == -1)
errExit("semget()");
arg.buf = &ds;
// 세마포어를 생성하는 프로세스가 semop를 호출할 때까지 대기
for (j = 0; j < MAX_TRIES; ++j) {
if(semctl(semid, 0, IPC_STAT, arg) == -1)
errExit("semctl()");
// 세마포어 생성이 완료되었다면, 루프 종료
if(ds.sem_otime != 0)
break;
sleep(1);
}
}
if(ds.sem_otime == 0)
fatal("Semaphore not initialized yet.");
// 0번 세마포어 값 조회
int semval = semctl(semid, 0, GETVAL, 0);
printf("val = %d\n", semval);
// 세마포어 값을 -1한다. -1이 가능할 때까지 대기함.
struct sembuf sop;
sop.sem_num = 0;
sop.sem_op = -1;
sop.sem_flg = 0;
if(semop(semid, &sop, 1) == -1) {
errExit("semop()");
}
/*
여기서 만일 semop에 의해 블록되고 있는 상태에서 SIGINT등을 받아서 블록이 중단되면,
세마포어를 해제하는 작업이 수행되지 않기 때문에, 다른 프로세스들이 영원히 진입할 수 없는 문제가 생김.
*/
// 세마포어로 보호해야 하는 '작업'을 수행
printf("job start..\n");
sleep(5);
printf("job end..\n");
// 세마포어 값을 +1한다. 세마포어에 대기하고 있는 다른 프로세스들이 '작업'으로 진입한다.
sop.sem_num = 0;
sop.sem_op = 1;
sop.sem_flg = 0;
if(semop(semid, &sop, 1) == -1) {
errExit("semop()");
}
}
示例13: main
int main()
{
int running = 1;
void *shared_memory = (void *)0;
struct shared_use_st *shared_stuff;
int shmid;
srand((unsigned int)getpid());
//get the semaphores
sem_id = semget((key_t)1233, 1, 0666 | IPC_CREAT);
sem_id2 = semget((key_t)1235, 1, 0666 | IPC_CREAT);
sem_id3 = semget((key_t)1236, 1, 0666 | IPC_CREAT);
/*
*sets the semaphores to the required values if it fails program ends
*/
if (!set_mutex()| !set_available()| !set_empty()) {
fprintf(stderr, "Failed to initialize semaphore\n");
exit(EXIT_FAILURE);
}
//get shared memory
shmid = shmget((key_t)1231, (sizeof(struct shared_use_st)- sizeof(int)) , 0666 | IPC_CREAT);
if (shmid == -1) {
fprintf(stderr, "shmget failed prod\n");
exit(EXIT_FAILURE);
}
/* We now make the shared memory accessible to the program. */
shared_memory = shmat(shmid, (void *)0, 0);
if (shared_memory == (void *)-1) {
fprintf(stderr, "shmat failed\n");
exit(EXIT_FAILURE);
}
printf("Memory attached at %X\n", (void *)shared_memory);
/* The next portion of the program assigns the shared_memory segment to shared_stuff,
Reads in from the input file test4k.txt into the buffer ibuffer string of size BUFSIZ, then the
loop continually copies text from ibuffer into the buffers in shared memory which take 128 bytes of char until a value less than 128 is written which means approached end of text then it sleeps and deletes the semaphores */
shared_stuff = (struct shared_use_st *)shared_memory;
//shared_stuff->written_by_you = 0;
char ibuffer[BUFSIZ]; // input buffer
int in; // variable to hold reference to input file
int index=0; // current index of element in array of structs in shared memory
int len; // length read
int tot = 0; // Total length read
in = open("test4k.txt",O_RDONLY);
len = read(in,ibuffer, sizeof(ibuffer));
while(running){
for(int i = 0; i<= len; i+=128){
sleep(2);
if((len-i)<128){
//if value written is less than 128 delete semaphores
shared_stuff->msgs[index].written = len-i;
memcpy(shared_stuff->msgs[index].some_text, ibuffer + (len-i), (len-i));
tot+= shared_stuff->msgs[index].written;
printf("Producer: bytes written val %d\n", shared_stuff->msgs[index].written);
printf("Producer: Total bytes written val %d\n", tot);
sleep(10);
del_semvalue();
exit(EXIT_SUCCESS);
}
else{
empty_p();
mutex_p();
shared_stuff->msgs[index].written = 128;
printf("Producer: bytes written val %d\n", shared_stuff->msgs[index].written);
memcpy(shared_stuff->msgs[index].some_text,ibuffer + i,128);
tot+= shared_stuff->msgs[index].written;
index = (index+1)%k;
mutex_v();
available_v();
}
}
}
//.........这里部分代码省略.........
示例14: main
main()
{
semid=semget(IPC_PRIVATE, 3, 0666);
seminfo.val=1;
semctl(semid,C_C, SETVAL,seminfo);
seminfo.val=0;
semctl(semid,C_D, SETVAL,seminfo);
shmid=shmget(IPC_PRIVATE, 2, 0666);//for storing command and port
shmid_s =shmget(IPC_PRIVATE, 100, 0666);//for storing file name
shmptr=(int *)shmat(shmid, 0, 0);
shmptr_s=(char *)shmat(shmid_s, 0, 0);
*(shmptr)=0;
*(shmptr+1)=0;
int cc = getpid();
int cd = fork();
int d= 4;
int32_t conv;
int code;
//Control Process of Client
if(getpid() == cc)
{
//printf("In CC...");
int tcpC1 ;
struct sockaddr_in serv_addr;
int i;
char buf[100];
//Socket Creation
if ((tcpC1 = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("Unable to create socket\n");
exit(0);
}
//Initialing the socket variables
serv_addr.sin_family= AF_INET;
serv_addr.sin_addr.s_addr=inet_addr("127.0.0.1");
serv_addr.sin_port=htons(50000);
//Connecting to server
if ((connect(tcpC1, (struct sockaddr *) &serv_addr,sizeof(serv_addr))) < 0)
{
printf("Unable to connect to server\n");
exit(0);
}
for(i=0;i<100;i++)
buf[i]='\0';
while(1)
{
semop(semid,&WaitC,1);
printf(">");
fgets(buf,100,stdin);
write(tcpC1, buf, strlen(buf) + 1);//sending command to server
int k =0,index =0;
char a[100],b[100];
while(1)
{
if(buf[k]==' ' || buf[k]=='\0')
break;
else
{
a[index]=buf[k];
index++;
}
k++;
}
a[index]='\0';//command saved
k++;
index=0;
while(1)
{
if((strcmp(a,"quit")==0) || buf[k]=='\0')
break;
else
{
b[index]=buf[k];
index++;
}
k++;
}
b[index]='\0';//argument saved
int flag = 0;
//.........这里部分代码省略.........
示例15: shmget
int Linda::init(key_t shm_key)
{
// try to create new shared memory segment
shmId = shmget(shm_key, 4 + MAX_TUPLES*(TUPLE_MAX_SIZE + 1), IPC_CREAT | IPC_EXCL | 0777);
// try to create new shared memory segment
shmId = shmget(shm_key, 4 + MAX_TUPLES*(TUPLE_MAX_SIZE + 1), IPC_CREAT | IPC_EXCL | 0777);
if (shmId < 0 && errno == EEXIST) // someone already created shm segment
{
// connect to existing shm segment
shmId = shmget(shm_key, 4 + MAX_TUPLES*(TUPLE_MAX_SIZE + 1), IPC_CREAT | 0777);
if(shmId == -1)
{
int err = errno;
if (debug) std::cerr << "[Linda] Error connecting to shared memory segment." << std::endl;
return err;
}
// read basic environment data (process counter and semaphores' table id)
if ((shm = (SharedMemory*)shmat(shmId, 0, 0)) < 0)
{
int err = errno;
if (debug) std::cerr << "[Linda] Error mapping shared memory segment." << std::endl;
return err;
}
if (debug) std::cout << "[Linda] semKey=" << shm->semKey;
if ((semId = semget(shm->semKey, 3, IPC_CREAT | 0777)) == -1)
{
int err = errno;
if (debug) std::cerr << "[Linda] Error obtaining existing semaphores." << std::endl;
return errno;
}
if (debug) std::cout << "[Linda] semId="<<semId << std::endl;
struct sembuf getCriticalSection[1] =
{
SEM_READ, 1, 0,
};
if (semop(semId, getCriticalSection, sizeof(getCriticalSection)/sizeof(sembuf)) < 0)
{
int err = errno;
if (debug)
std::cerr << "[Linda input] Error refreshing readers' semaphore limit." << std::endl;
return err;
}
return 0;
}
else if (shmId == -1)
{
int err = errno;
if (debug)
std::cerr << "[Linda] Error creating new shared memory segment." << std::endl;
return err;
}
// we created new shared memory segment, so fill it with empty environment data
if ((long)(shm = (SharedMemory*)shmat(shmId, 0, 0)) < 0)
{
int err = errno;
if (debug)
std::cerr << "[Linda] Error mapping shared memory segment." << std::endl;
return err;
}
int key = 1234;
if ((semId = semget(key, 3, IPC_CREAT | IPC_EXCL | 0777)) == -1)
{
int err = errno;
if (debug)
std::cerr << "[Linda] Error creating semaphore set." << std::endl;
return err;
}
if (debug)
std::cout << "[Linda] semId=" << semId << std::endl;
shm->semKey = key;
for (int i = 0; i < MAX_TUPLES; i++)
shm->tupleArray[i].valid = TUPLE_INVALID;
struct sembuf increment[1] =
{
SEM_READ, 1, 0,
};
if (semop(semId, increment, sizeof(increment)/sizeof(sembuf)) < 0)
{
int err = errno;
if (debug)
std::cerr << "[Linda input] Error refreshing readers' semaphore limit." << std::endl;
return err;
}
if (debug)
std::cout<<"[Linda] Incremented sem_read"<<std::endl;
return 0;
}