2010-09-07 116 views
0

我想在我的程序中實現EINVAL,EPERM,ESRCH。在Kill中實現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; 
} 

} 

當我編譯程序,我得到以下錯誤。

[email protected]:/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)
[email protected]:/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; 
    } 

} 

感謝。

+2

您可能應該使用'strerror'或'perror'來獲取錯誤信息,而不是寫自己的。它更簡單,更簡潔,並且在許多系統上,它將免費爲您翻譯成用戶的母語。 – 2010-09-07 13:10:13

+0

感謝您的意見。 – Searock 2010-09-07 13:13:31

回答

4

你正在試圖做的都不行什麼,首先你應該#include <errno.h>(因爲這就是errno定義,爲是錯誤代碼)。 其次,不要調用你的本地返回值變量errno(因爲它存在並且是錯誤代碼的位置)。

例如。

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

int rc; 
/* ... */ 

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

什麼是SIGHUP?這是一個信號? – Searock 2010-09-07 12:42:02

+0

+1非常感謝,你能告訴我什麼是errno? – Searock 2010-09-07 12:47:08

+2

'SIGHUP'是一個信號(與代碼中的'1'相同),有關errno的更多信息,請參閱http://en.wikipedia.org/wiki/Errno – Hasturkun 2010-09-07 12:59:22