我正在尝试在我的程序中实现 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/