tags:

views:

66

answers:

1

I am trying to implement EINVAL, EPERM, ESRCH in my program.

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.

Here's my source code :

#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;
 }

}

And when I compile the program I get the following errors.

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$

So where are EINVAL, EPERM, ESRCH defined? Do I need to define any additional header file? Or I am implementing it in a wrong way?

Updated Code [working code] :

#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;
    }

}

Thanks.

+3  A: 

What you're trying to do won't work, first you should #include <errno.h> (as that's where errno is defined, as are the error codes). Second, don't call your local return value variable errno (as that exists and is where the error code will be).

eg.

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

int rc;
/* ... */

rc = kill(pid, SIGHUP);
if (rc != 0)
{
    switch (errno) {...}
}
Hasturkun
what is SIGHUP? is it a signal?
Searock
+1 thanks a lot, can you tell me what is errno?
Searock
`SIGHUP` is a signal (the same as the `1` in your code), for more information about errno see http://en.wikipedia.org/wiki/Errno
Hasturkun
Thanks again : )
Searock