gpt4 book ai didi

c++ - 与 sigsuspend() 的死锁

转载 作者:太空宇宙 更新时间:2023-11-04 11:33:41 30 4
gpt4 key购买 nike

我试图同步父亲和 child ,下面的代码不起作用(显然 usr_interrupt++ 不是原子的)。信号量似乎也无济于事。

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <unistd.h>
#include <cstdlib>
#include <iostream>
#include <unistd.h>
#include <cstring>
#include <string>
#include <semaphore.h>
#include <fcntl.h>

using namespace std;

/* When a SIGUSR1 signal arrives, set this variable. */
volatile sig_atomic_t usr_interrupt;
sem_t *mutex;
char* SEM_NAME;

void
synch_signal (int sig)
{
// sem_wait(mutex);
usr_interrupt++;
// sem_post(mutex);
}

/* The child process executes this function. */
void
child_function (void)
{

/* Perform initialization. */
cerr << "I'm here!!! My pid is " << (int)getpid() << " my usr_int=" << usr_interrupt << endl;
/* Let parent know you're done. */
kill (getppid (), SIGUSR1);
/* Continue with execution. */
cerr << "Bye, now...." << endl;
exit(0);
}

int
main (void)
{
usr_interrupt = 0;

string s_sem_name = "lir";
SEM_NAME = new char[s_sem_name.size()+1];
memcpy(SEM_NAME, s_sem_name.c_str(), s_sem_name.size());
SEM_NAME[s_sem_name.size()] = '\0';
mutex = sem_open (SEM_NAME,O_CREAT,0644,1);
if(mutex == SEM_FAILED) {
perror("unable to create semaphore");
sem_unlink(SEM_NAME);
exit(-1);
}


struct sigaction usr_action;
sigset_t mask, oldmask;
pid_t child_id, child_id2;

/* Set up the mask of signals to temporarily block. */
sigemptyset (&mask);
sigaddset (&mask, SIGUSR1);

/* Establish the signal handler.*/
usr_action.sa_handler = synch_signal;
usr_action.sa_flags = 0;
sigaction (SIGUSR1, &usr_action, NULL);

/* Create the 2 children processes. */
child_id = fork ();
if (child_id == 0)
child_function ();

child_id2 = fork();
if (child_id2 == 0)
child_function ();

/* Wait for a signal to arrive. */
sigprocmask (SIG_BLOCK, &mask, &oldmask);
while (usr_interrupt != 2) {
sigsuspend (&oldmask);
}
sigprocmask (SIG_UNBLOCK, &mask, NULL);


/* Now continue execution. */
puts ("That's all, folks!");

return 0;
}

任何人都可以提出修复建议吗? (我不能使用线程)最好的,-- 里昂

最佳答案

You can't count signals.相同类型的两个信号与该类型的一个信号具有相同的语义。您可以使用两种不同的信号类型,例如 USR1 和 USR2。但老实说,您不应该将信号用作通信机制。使用合理的东西,例如管道。

关于c++ - 与 sigsuspend() 的死锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9534229/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com