Exemple #1
0
int
main(int argc, char *argv[])
{
  char str[MAX_CMD_LEN];  /* Command to be executed by system() */
  int status;  /* Status return from system() */


  for (;;) {    /* Read and execute a shell command */
    printf("Command: ");
    fflush(stdout);
    if (fgets(str, MAX_CMD_LEN, stdin) == NULL)
      break;    /* end-of-file */

    status = system(str);
    printf("system() returned: status=0x%04x (%d,%d)\n",
        (unsigned int) status, status >> 8, status & 0xff);
    if (status == -1) {
      errExit("system");
    } else {
      if (WIFEXITED(status) && WEXITSTATUS(status) == 127)
        printf("(Probably) could not invoke shell\n");
      else
        /* Shell successfully executed command */
        printWaitStatus(NULL, status);
    }
  }
  exit(EXIT_SUCCESS);
}
static void
sigchldHandler(int sig)
{
    int status, savedErrno;
    pid_t childPid;

    /* UNSAFE: This handler uses non-async-signal-safe functions
       (printf(), printWaitStatus(), currTime(); see Section 21.1.2) */

    savedErrno = errno;         /* In case we modify 'errno' */

    printf("%s handler: Caught SIGCHLD\n", currTime("%T"));

    while ((childPid = waitpid(-1, &status, WNOHANG)) > 0) {
        printf("%s handler: Reaped child %ld - ", currTime("%T"),
                (long) childPid);
        printWaitStatus(NULL, status);
        numLiveChildren--;
    }

    if (childPid == -1 && errno != ECHILD)
        errMsg("waitpid");

    sleep(5);           /* Artificially lengthen execution of handler */
    printf("%s handler: returning\n", currTime("%T"));

    errno = savedErrno;
}
static void
sigchldHandler(int sig)
{
  int status, savedErrno;
  pid_t childPid;

  savedErrno = errno; /* In case we modify 'errno' */

  printf("%s handler: Caught SIGCHLD\n", currTime("%T"));

  while ((childPid = waitpid(-1, &status, WNOHANG)) > 0) {
    printf("%s handler: Reaped child %ld - ", currTime("%T"),
      (long) childPid);
    printWaitStatus(NULL, status);
   numLiveChildren--;
  }

  if (childPid == -1 && errno != ECHILD)
    errMsg("waitpid");

  sleep(5);
  printf("%s handler: returning\n", currTime("%T"));

  errno = savedErrno;
}
Exemple #4
0
int main(int argc,char *argv[])
{
	char pat[PAT_SIZE];
        char popenCmd[PCMD_BUF_SIZE];
        FILE *fp;
        Boolean badPattern;
        int len,status,fileCnt,j;
        char pathname[PATH_MAX];

 
        for(;;){
           printf("pattern: ");
           fflush(stdout);
           if(fgets(pat,PAT_SIZE,stdin)==NULL)
             break;
           len=strlen(pat);
           if(len<=1)
             continue;
 
           if(pat[len-1]=='\n')
             pat[len-1]='\0';

          for(j=0,badPattern=FALSE;j<len && !badPattern;j++)
             if(!isalnum((unsigned char)pat[j]) && strchr("_*?[^-].",pat[j])==NULL)
                badPattern=TRUE;

          if(badPattern){
            printf("Bad pattern character:%c\n",pat[j-1]);
            continue;
          }

          snprintf(popenCmd,PCMD_BUF_SIZE,POPEN_FMT,pat);
          popenCmd[PCMD_BUF_SIZE-1]='\0';

          fp=popen(popenCmd,"r");
          if(fp==NULL){
            printf("popen() failed\n");
            continue;
          }  
 
          fileCnt=0;
          while(fgets(pathname,PATH_MAX,fp)!=NULL){
               printf("%s",pathname);
               fileCnt++;
          }
 
          status=pclose(fp);
          printf(" %d matching file%s\n",fileCnt,(fileCnt!=1)?"s":"");
          printf(" pclose() status=%#x\n",(unsigned int)status);
          if(status!=-1)
             printWaitStatus("\t",status);
         
   
       } 
      
       exit(EXIT_SUCCESS);
}
Exemple #5
0
int
main(int argc, char *argv[])
{
    int status;
    pid_t childPid;

    if (argc > 1 && strcmp(argv[1], "--help") == 0)
        usageErr("%s [exit-status]\n", argv[0]);

    switch (fork()) {
    case -1:
        errExit("fork");

    case 0:             /* Child: either exits immediately with given
                           status or loops waiting for signals */
        printf("Child started with PID = %ld\n", (long) getpid());
        if (argc > 1)                   /* Status supplied on command line? */
            exit(getInt(argv[1], 0, "exit-status"));
        else                            /* Otherwise, wait for signals */
            for (;;)
                pause();
        exit(EXIT_FAILURE);             /* Not reached, but good practice */

    default:            /* Parent: repeatedly wait on child until it
                           either exits or is terminated by a signal */
        for (;;) {
            childPid = waitpid(-1, &status, WUNTRACED
#ifdef WCONTINUED       /* Not present on older versions of Linux */
                               | WCONTINUED
#endif
                              );
            if (childPid == -1)
                errExit("waitpid");

            /* Print status in hex, and as separate decimal bytes */

            printf("waitpid() returned: PID=%ld; status=0x%04x (%d,%d)\n",
                   (long) childPid,
                   (unsigned int) status, status >> 8, status & 0xff);
            printWaitStatus(NULL, status);

            if (WIFEXITED(status) || WIFSIGNALED(status))
                exit(EXIT_SUCCESS);
        }
    }
}
Exemple #6
0
static void sigChldHandler(int sig)
{
    int status, savedErrno;
    pid_t childPid;

    savedErrno = errno;
    printf("%s handler: Caught SIGCHLD\n", currTime("%T"));

    while((childPid = waitpid(-1, &status, WNOHANG)) > 0){
        printf("%s handler: Reaped child %jd - ", currTime("%T"),
                (intmax_t) childPid);
        printWaitStatus(NULL, status);
        --numLiveChildren;
    }

    if(childPid == -1 && errno != ECHILD)
        errMsg("waitpid()");

    printf("%s handler: returning\n", currTime("%T"));

    errno = savedErrno;
}
Exemple #7
0
int main(int argc, char *arv[])
{
	char str[MAX_CMD_LEN];
	int status;

	while(1){
		printf("Command: ");
		fflush(stdout);
		scanf("%s", str);
		status = system(str);
		printf("system() returned: status=0x%04x (%d,%d)\n", (unsigned int)status, status >> 8, status & 0xff);
		
		if(status == -1){
			errExit("system");
		}else{
			if(WIFEXITED(status) && WEXITSTATUS(status) == 127)
				printf("(Probably) could not invoke shell\n");
			else
				printWaitStatus(NULL, status);
		}
	}
	exit(EXIT_SUCCESS);
}
int
main(int argc, char *argv[])
{
    char pat[PAT_SIZE];                 /* Pattern for globbing */
    char popenCmd[PCMD_BUF_SIZE];
    FILE *fp;                           /* File stream returned by popen() */
    Boolean badPattern;                 /* Invalid characters in 'pat'? */
    int len, status, fileCnt, j;
    char pathname[PATH_MAX];

    for (;;) {                  /* Read pattern, display results of globbing */
        printf("pattern: ");
        fflush(stdout);
        if (fgets(pat, PAT_SIZE, stdin) == NULL)
            break;                      /* EOF */
        len = strlen(pat);
        if (len <= 1)                   /* Empty line */
            continue;

        if (pat[len - 1] == '\n')       /* Strip trailing newline */
            pat[len - 1] = '\0';

        /* Ensure that the pattern contains only valid characters,
           i.e., letters, digits, underscore, dot, and the shell
           globbing characters. (Our definition of valid is more
           restrictive than the shell, which permits other characters
           to be included in a filename if they are quoted.) */

        for (j = 0, badPattern = FALSE; j < len && !badPattern; j++)
            if (!isalnum((unsigned char) pat[j]) &&
                    strchr("_*?[^-].", pat[j]) == NULL)
                badPattern = TRUE;

        if (badPattern) {
            printf("Bad pattern character: %c\n", pat[j - 1]);
            continue;
        }

        /* Build and execute command to glob 'pat' */

        snprintf(popenCmd, PCMD_BUF_SIZE, POPEN_FMT, pat);

        fp = popen(popenCmd, "r");
        if (fp == NULL) {
            printf("popen() failed\n");
            continue;
        }

        /* Read resulting list of pathnames until EOF */

        fileCnt = 0;
        while (fgets(pathname, PATH_MAX, fp) != NULL) {
            printf("%s", pathname);
            fileCnt++;
        }

        /* Close pipe, fetch and display termination status */

        status = pclose(fp);
        printf("    %d matching file%s\n", fileCnt, (fileCnt != 1) ? "s" : "");
        printf("    pclose() status = %#x\n", (unsigned int) status);
        if (status != -1)
            printWaitStatus("\t", status);
    }

    exit(EXIT_SUCCESS);
}
Exemple #9
0
int
main(int argc, char *argv[])
{
    const int STACK_SIZE = 65536;       /* Stack size for cloned child */
    char *stack;                        /* Start of stack buffer area */
    char *stackTop;                     /* End of stack buffer area */
    int flags;                          /* Flags for cloning child */
    ChildParams cp;                     /* Passed to child function */
    const mode_t START_UMASK = S_IWOTH; /* Initial umask setting */
    struct sigaction sa;
    char *p;
    int status;
    ssize_t s;
    pid_t pid;

    printf("Parent: PID=%ld PPID=%ld\n", (long) getpid(), (long) getppid());

    /* Set up an argument structure to be passed to cloned child, and
       set some process attributes that will be modified by child */

    cp.exitStatus = 22;                 /* Child will exit with this status */

    umask(START_UMASK);                 /* Initialize umask to some value */
    cp.umask = S_IWGRP;                 /* Child sets umask to this value */

    cp.fd = open("/dev/null", O_RDWR);  /* Child will close this fd */
    if (cp.fd == -1)
        errExit("open");

    cp.signal = SIGTERM;                /* Child will change disposition */
    if (signal(cp.signal, SIG_IGN) == SIG_ERR)
        errExit("signal");

    /* Initialize clone flags using command-line argument (if supplied) */

    flags = 0;
    if (argc > 1) {
        for (p = argv[1]; *p != '\0'; p++) {
            if      (*p == 'd') flags |= CLONE_FILES;
            else if (*p == 'f') flags |= CLONE_FS;
            else if (*p == 's') flags |= CLONE_SIGHAND;
            else if (*p == 'v') flags |= CLONE_VM;
            else usageError(argv[0]);
        }
    }

    /* Allocate stack for child */

    stack = malloc(STACK_SIZE);
    if (stack == NULL)
        errExit("malloc");
    stackTop = stack + STACK_SIZE;  /* Assume stack grows downward */

    /* Establish handler to catch child termination signal */

    if (CHILD_SIG != 0) {
        sigemptyset(&sa.sa_mask);
        sa.sa_flags = SA_RESTART;
        sa.sa_handler = grimReaper;
        if (sigaction(CHILD_SIG, &sa, NULL) == -1)
            errExit("sigaction");
    }

    /* Create child; child commences execution in childFunc() */

    if (clone(childFunc, stackTop, flags | CHILD_SIG, &cp) == -1)
        errExit("clone");

    /* Parent falls through to here. Wait for child; __WCLONE option is
       required for child notifying with signal other than SIGCHLD. */

    pid = waitpid(-1, &status, (CHILD_SIG != SIGCHLD) ? __WCLONE : 0);
    if (pid == -1)
        errExit("waitpid");

    printf("    Child PID=%ld\n", (long) pid);
    printWaitStatus("    Status: ", status);

    /* Check whether changes made by cloned child have affected parent */

    printf("Parent - checking process attributes:\n");
    if (umask(0) != START_UMASK)
        printf("    umask has changed\n");
    else
        printf("    umask has not changed\n");

    s = write(cp.fd, "Hello world\n", 12);
    if (s == -1 && errno == EBADF)
        printf("    file descriptor %d has been closed\n", cp.fd);
    else if (s == -1)
        printf("    write() on file descriptor %d failed (%s)\n",
                cp.fd, strerror(errno));
    else
        printf("    write() on file descriptor %d succeeded\n", cp.fd);

    if (sigaction(cp.signal, NULL, &sa) == -1)
        errExit("sigaction");
    if (sa.sa_handler != SIG_IGN)
        printf("    signal disposition has changed\n");
    else
        printf("    signal disposition has not changed\n");

    exit(EXIT_SUCCESS);
}
int main(int argc, char *argv[])
{
	int sock, ret, server_fd, pid, status;
	struct sockaddr_in addr_in;
	socklen_t addrlen = sizeof(addr_in);

	int c, level = LOG_DEBUG, sysl = 0;
	int option_index = 0;
	char *short_options = "sh";
	struct option long_options[] = {
		{"syslog", no_argument, 0, 's'},
		{"level", required_argument, 0, 'l'},
		{"help", required_argument, 0, 'h'}
	};

	while ((c = getopt_long_only(argc, argv, short_options, long_options, &option_index)) != -1)
		switch (c) {
		case 's':
			sysl = 1;
			break;
		case 'l':
			level = atoi(optarg);
			break;
		case 'h':
			printf("Usage %s [OPTIONS]\n", argv[0]);
			printf("\nCommand line options\n\n");
			printf("\t\t-l <level>\t log level\n");
			printf("\t\t-s\t use of syslog\n");
			return 0;
		}

	logger_init(sysl, level);

	server_fd = create_tcp_server(SERVER_PORT);
	if (server_fd < 0) {
		ERROR("cannot create server socket");
		return 0;
	}

	while (1) {
		sock = accept(server_fd, (struct sockaddr *)&addr_in, &addrlen);
		if (sock < 0) {
			if (errno == EAGAIN || errno == EWOULDBLOCK)
				goto waitpid;
			ERROR("socket accept error %s", strerror(errno));
			return -1;
		}

		ret = fork();
		if (ret < 0) {
			ERROR("fork error %s", strerror(errno));
			break;
		}
		if (ret == 0) {
			char buffer[50];

			DEBUG("New process on socket %d", sock);

			snprintf(buffer, sizeof(buffer), resp_xml, status_str[0]);
			ret = send_resp(sock, buffer, strlen(buffer));
			if (ret < 0)
				ERROR("send_resp error %d", ret);

			handle_request(sock);

			DEBUG("close sock %d", sock);
			close(sock);

			exit(0);
		}

		close(sock);

	waitpid:
		do {
			pid = waitpid(0, &status, WNOHANG);
			if (pid < 0) {
				if (errno != ECHILD)
					ERROR("waitpid error %s", strerror(errno));
				break;
			} else if (pid) {
				char str[100];
				printWaitStatus(str, status);
				INFO("waitpid() PID=%ld status=0x%04x: %s",
				      (long) pid, (unsigned int) status, str);
			}
		} while (pid);

		sleep(1);
	}
	return 0;
}