c - 在 Kill() 中实现 EINVAL、EPERM、ESRCH

标签 c unix ubuntu posix

我正在尝试在我的程序中实现 EINVAL、EPERM、ESRCH。

ERRORS
EINVAL An invalid signal was specified.
EPERM The process does not have permission to send the signal to any of the target processes. ESRCH The pid or process group does not exist.

这是我的源代码:

#include <stdio.h>
#include <sys/types.h>
#include <signal.h>
#include <unistd.h>

int main(void)
{

 int errno, pid;

 puts("Enter a process id : ");
 scanf("%d", &pid);

    errno = kill(pid, 1);

 if(errno == -1)
 {
  printf("Cannot find or kill the specified process\n");

 }


 switch(errno)
 {
  case EINVAL:
   printf("An invalid signal was specified.\n");
   break;

  case EPERM:
   printf("The process does not have permission to send the signal to any of the target processes.\n");
   break;

  case ESRCH:
   printf("The  pid or process group does not exist.");
   break;
 }

}

当我编译程序时出现以下错误。

unipro@ubuguest:/SoftDev/ADSD/Module 1/Unit 1/Pratice/C/C_adv/unix$ cc killApp.c -o killApp
killApp.c: In function ‘main’:
killApp.c:29: error: ‘EINVAL’ undeclared (first use in this function)
killApp.c:29: error: (Each undeclared identifier is reported only once
killApp.c:29: error: for each function it appears in.)
killApp.c:33: error: ‘EPERM’ undeclared (first use in this function)
killApp.c:37: error: ‘ESRCH’ undeclared (first use in this function)
unipro@ubuguest:/SoftDev/ADSD/Module 1/Unit 1/Pratice/C/C_adv/unix$

那么EINVAL、EPERM、ESRCH是在哪里定义的呢?我需要定义任何额外的头文件吗?或者我以错误的方式实现它?

更新代码[工作代码]:

#include <stdio.h>
#include <sys/types.h>
#include <signal.h>
#include <unistd.h>
#include <errno.h>

int main(void)
{

    int status, pid;

    puts("Enter a process id : ");
    scanf("%d", &pid);

    status = kill(pid, 1);



    switch(errno)
    {
        case EINVAL:
            printf("An invalid signal was specified.\n");
            break;

        case EPERM:
            printf("The process does not have permission to send the signal to any of the target processes.\n");
            break;

        case ESRCH:
            printf("The  pid or process group does not exist.");
            break;
    }

}

谢谢。

最佳答案

你想做的是行不通的,首先你应该#include <errno.h> (因为这是定义 errno 的地方,错误代码也是如此)。 其次,不要调用本地返回值变量 errno(因为它存在并且是错误代码所在的位置)。

例如。

#include <errno.h>
/* ... */

int rc;
/* ... */

rc = kill(pid, SIGHUP);
if (rc != 0)
{
    switch (errno) {...}
}

关于c - 在 Kill() 中实现 EINVAL、EPERM、ESRCH,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3658668/

相关文章:

linux - cURL:如果连接超时/挂起,重新启动连接

c - 在按Ctrl + D后停止用户输入需要按2次。为什么?

C : unknown memory issue ? - 二叉树练习

从十进制转换为非十进制并打印(无字符串、数组和递归)

ubuntu - 无法在 Sublime text 2 中安装包控件

c++ - 在 Ubuntu 中学习 OpenGL

ubuntu - SSLv3 警报握手失败

c - 使用 DMA 将图像加载到 Visual Boy Advance (VBA)

c++ - 执行虚拟语句

c - 将长时间运行的子进程的输出重定向到父进程