【问题标题】:Kill() function between two processes两个进程之间的 Kill() 函数
【发布时间】:2016-12-28 21:24:59
【问题描述】:

我可以使用 kill() 函数向另一个进程发送信号吗?这应该是可能的,但是 kill() 失败了,我不明白为什么。 我有两个程序(process_1 和 process_2)。第一个应该设置一个信号处理程序来增加一个变量,而不是创建一个使用 execve 并加载 process_2 的子级。另一个程序应该使用 kill() 发送信号。我使用共享内存通过结构共享 process_1 的 pid(因为我还有其他变量要共享)。第一个程序的代码如下:

#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <signal.h>
#include <errno.h>
#include <time.h>
#include <sys/ipc.h>
#include <sys/types.h>
#include <sys/shm.h>
#include <sys/wait.h>

#define KEY_SM 1234
static int value_to_change=0;


typedef struct keys{
    pid_t pid_process;
}keynote;


static void test_handler(int signo){
    if(signo=SIGUSR1){
        printf("received SIGUSR1\n");
        value_to_change++;
    }
}


int main(){
    if((signal(SIGUSR1, test_handler))==SIG_ERR) perror("Errore allocazione SIGUSR1");
    int flags = S_IRUSR|S_IWUSR|IPC_CREAT;
    size_t shm_size = sizeof(keynote);
    int shm_id = shmget(KEY_MC, shm_size, flags);
    keynote *chv = shmat(shm_id, NULL, 0);
    chv->pid_process=getpid();
    printf("%d\n",chv->pid_process);


    int process_2;
    process_2=fork();
    if(process_2==0){
        char* argv[]={"process_1", "process_2", NULL};
        if((execve("process_2", argv, NULL))<0) perror("execve error");
    exit(0);
    }else if(process_2<0)perror("fork error");

    return 0;
}

第二个程序代码是:

#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <signal.h>
#include <errno.h>
#include <time.h>
#include <sys/ipc.h>
#include <sys/types.h>
#include <sys/shm.h>
#include <sys/wait.h>

 #define KEY_SM 1234

    typedef struct keys{
        pid_t pid_process;
    }keynote;


static void signal_to_send(pid_t process){
    int ret=kill(process, SIGUSR1);
    printf("%d", ret);
    }
}


int main(int argc, char **argv){
    int pid_of_process_1;
    int flags = S_IRUSR|S_IWUSR|IPC_CREAT;
    size_t shm_size = sizeof(keynote);

    int shm_id = shmget(KEY_MC, shm_size, flags);  
    keynote *chv = shmat(shm_id, NULL, 0);
    signal_to_send(chv->pid_process);

    return 0;
}

【问题讨论】:

  • 您实际上并没有提出问题。 “我遇到了一些麻烦”既不是一个问题,也不是对您的具体问题的一个很好的描述。请查看:How do I ask a good question?
  • process_1 不等待process_2。它只是立即退出。此时process_2 甚至可能还没有开始。所以当process_2发出信号时,process_1很可能已经不存在了。
  • 哦,好的。知道了。谢谢
  • if(signo=SIGUSR1){ -->> if(signo == SIGUSR1){ 另外:您不应该在信号处理程序中使用 printf()。

标签: c


【解决方案1】:

process_1 不会等待process_2。它只是立即退出。此时process_2 甚至可能还没有开始。所以当process_2 发送信号时,process_1 很可能已经不存在了。 – 凯勒姆

【讨论】:

    猜你喜欢
    • 2011-08-09
    • 1970-01-01
    • 2013-02-14
    • 1970-01-01
    • 2021-04-28
    • 1970-01-01
    • 1970-01-01
    • 2012-10-11
    • 2013-01-03
    相关资源
    最近更新 更多