Example #1
0
static int recv_fd(int c)
{
    int fd;
    uint8_t msgbuf[CMSG_SPACE(sizeof(fd))];
    struct msghdr msg = {
        .msg_control = msgbuf,
        .msg_controllen = sizeof(msgbuf),
    };
    struct cmsghdr *cmsg;
    struct iovec iov;
    uint8_t req[1];
    ssize_t len;

    cmsg = CMSG_FIRSTHDR(&msg);
    cmsg->cmsg_level = SOL_SOCKET;
    cmsg->cmsg_type = SCM_RIGHTS;
    cmsg->cmsg_len = CMSG_LEN(sizeof(fd));
    msg.msg_controllen = cmsg->cmsg_len;

    iov.iov_base = req;
    iov.iov_len = sizeof(req);

    msg.msg_iov = &iov;
    msg.msg_iovlen = 1;

    len = recvmsg(c, &msg, 0);
    if (len > 0) {
        memcpy(&fd, CMSG_DATA(cmsg), sizeof(fd));
        return fd;
    }

    return len;
}

static int net_bridge_run_helper(const char *helper, const char *bridge,
                                 Error **errp)
{
    sigset_t oldmask, mask;
    int pid, status;
    char *args[5];
    char **parg;
    int sv[2];

    sigemptyset(&mask);
    sigaddset(&mask, SIGCHLD);
    sigprocmask(SIG_BLOCK, &mask, &oldmask);

    if (socketpair(PF_UNIX, SOCK_STREAM, 0, sv) == -1) {
        error_setg_errno(errp, errno, "socketpair() failed");
        return -1;
    }

    /* try to launch bridge helper */
    pid = fork();
    if (pid < 0) {
        error_setg_errno(errp, errno, "Can't fork bridge helper");
        return -1;
    }
    if (pid == 0) {
        int open_max = sysconf(_SC_OPEN_MAX), i;
        char fd_buf[6+10];
        char br_buf[6+IFNAMSIZ] = {0};
        char helper_cmd[PATH_MAX + sizeof(fd_buf) + sizeof(br_buf) + 15];

        for (i = 3; i < open_max; i++) {
            if (i != sv[1]) {
                close(i);
            }
        }

        snprintf(fd_buf, sizeof(fd_buf), "%s%d", "--fd=", sv[1]);

        if (strrchr(helper, ' ') || strrchr(helper, '\t')) {
            /* assume helper is a command */

            if (strstr(helper, "--br=") == NULL) {
                snprintf(br_buf, sizeof(br_buf), "%s%s", "--br=", bridge);
            }

            snprintf(helper_cmd, sizeof(helper_cmd), "%s %s %s %s",
                     helper, "--use-vnet", fd_buf, br_buf);

            parg = args;
            *parg++ = (char *)"sh";
            *parg++ = (char *)"-c";
            *parg++ = helper_cmd;
            *parg++ = NULL;

            execv("/bin/sh", args);
        } else {
            /* assume helper is just the executable path name */

            snprintf(br_buf, sizeof(br_buf), "%s%s", "--br=", bridge);

            parg = args;
            *parg++ = (char *)helper;
            *parg++ = (char *)"--use-vnet";
            *parg++ = fd_buf;
            *parg++ = br_buf;
            *parg++ = NULL;

            execv(helper, args);
        }
        _exit(1);

    } else {
        int fd;
        int saved_errno;

        close(sv[1]);

        do {
            fd = recv_fd(sv[0]);
        } while (fd == -1 && errno == EINTR);
        saved_errno = errno;

        close(sv[0]);

        while (waitpid(pid, &status, 0) != pid) {
            /* loop */
        }
        sigprocmask(SIG_SETMASK, &oldmask, NULL);
        if (fd < 0) {
            error_setg_errno(errp, saved_errno,
                             "failed to recv file descriptor");
            return -1;
        }
        if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
            error_setg(errp, "bridge helper failed");
            return -1;
        }
        return fd;
    }
}
Example #2
0
int main(void) {
  ssize_t pagesize = sysconf(_SC_PAGESIZE);
  int fd;
  int fd2;
  size_t i;
  int err;
  pid_t parent_pid = getpid();
  pid_t pid;
  int status;

  fd = open(FILENAME, O_CREAT | O_EXCL | O_RDWR, 0600);
  fd2 = open(FILENAME, O_RDWR);
  test_assert(fd >= 0 && fd2 >= 0);

  unlink(FILENAME);

  atomic_printf("parent pid is %d\n", parent_pid);

  /* Write a page's worth of data. */
  for (i = 0; i < pagesize / sizeof(i); ++i) {
    ssize_t nwritten = write(fd, &i, sizeof(i));
    test_assert(nwritten == sizeof(i));
  }

  {
    struct flock64 lock = {
      .l_type = F_WRLCK, .l_whence = SEEK_SET, .l_start = 0, .l_len = pagesize, .l_pid = 0
    };

    atomic_printf("sizeof(flock64) = %zu\n", sizeof(lock));
    err = fcntl(fd, F_OFD_GETLK, &lock);
    if (err == -1 && errno == EINVAL)
    {
      // should we succeed when OFD locks are not supported?
      atomic_puts("EXIT-SUCCESS");
      return 0;
    }

    test_assert(0 == err);

    atomic_printf("before lock: type: %d, pid: %d\n", lock.l_type, lock.l_pid);
    test_assert(F_UNLCK == lock.l_type);

    lock.l_type = F_WRLCK;
    fcntl(fd, F_OFD_SETLK, &lock);
    test_assert(0 == err);

    /* Make sure our lock "took". */
    if (0 == (pid = fork())) {
      lock.l_type = F_RDLCK;
      err = fcntl(fd2, F_OFD_GETLK, &lock);
      test_assert(0 == err);

      atomic_printf("  after GETLK: type: %d, pid: %d\n", lock.l_type,
                    lock.l_pid);
      test_assert(F_WRLCK == lock.l_type && 0 == lock.l_start &&
                  pagesize == lock.l_len && -1 == lock.l_pid);

      lock.l_type = F_RDLCK;
      lock.l_pid = 0;
      err = fcntl(fd2, F_OFD_SETLKW, &lock);
      test_assert(0 == err);

      atomic_printf("  after SETLKW: type: %d, pid: %d\n", lock.l_type,
                    lock.l_pid);
      test_assert(F_RDLCK == lock.l_type && 0 == lock.l_start &&
                  pagesize == lock.l_len && 0 == lock.l_pid);

      atomic_puts("  releasing lock ...");
      lock.l_type = F_UNLCK;
      fcntl(fd2, F_OFD_SETLK, &lock);
      test_assert(0 == err);
      return 0;
    }

    atomic_puts("P: forcing child to block on LK, sleeping ...");
    usleep(500000);
    atomic_puts("P: ... awake, releasing lock");
    lock.l_type = F_UNLCK;
    fcntl(fd, F_OFD_SETLK, &lock);
    test_assert(0 == err);

    waitpid(pid, &status, 0);
    test_assert(WIFEXITED(status) && 0 == WEXITSTATUS(status));
  }

  atomic_puts("EXIT-SUCCESS");
  return 0;
}
Example #3
0
int job_wait(struct job *j, int async)
{
	int wait_status = 0, proc_still_running = 0;
	struct proc *p;
	pid_t pid;
	pid_t wait_on_me;

#define JOB_WAIT_CHANGE_GROUP
#ifdef JOB_WAIT_CHANGE_GROUP
	pid_t orig_pgid;
	int save;

	if(interactive)
		orig_pgid = getpgid(STDIN_FILENO);
#endif

rewait:
	if(interactive){
		if(j->tconf_got)
			term_attr_set(&j->tconf);
		else
			term_attr_orig();

#ifdef JOB_WAIT_CHANGE_GROUP
		term_give_to(j->gid);
		/*setpgid(getpid(), j->gid);*/
#endif
	}

	if(j->gid){
		wait_on_me = -j->gid;
	}else{
		struct proc *p = job_first_proc(j);

		if(p)
			wait_on_me = p->pid;
		else
			wait_on_me = j->proc->pid; /* guess */
	}

	pid = waitpid(wait_on_me, &wait_status,
			WUNTRACED | WCONTINUED | (async ? WNOHANG : 0));

	if(interactive){
#ifdef JOB_WAIT_CHANGE_GROUP
		save = errno;
		term_give_to(orig_pgid);
		/*setpgid(getpid(), orig_pgid);*/
		errno = save;
#endif

		term_attr_get(&j->tconf);
		j->tconf_got = 1;
		term_attr_ush();
	}


	if(pid == -1){
		if(errno == EINTR)
			goto rewait;
		else
			fprintf(stderr, "waitpid(%d [job %d: \"%s\"], async = %s): %s\n",
					-j->gid, j->job_id, j->cmd, async ? "true" : "false",
					strerror(errno));

		return 1;
	}else if(pid == 0 && async)
		return 0;


	for(p = j->proc; p; p = p->next)
		if(p->pid == pid){
			if(WIFSIGNALED(wait_status)){
				p->state = PROC_FIN;

				p->exit_sig = WTERMSIG(wait_status);
				p->exit_code = WEXITSTATUS(wait_status); /* 0 */
			}else if(WIFEXITED(wait_status)){
				p->state = PROC_FIN;

				p->exit_sig = 0;
				p->exit_code = WEXITSTATUS(wait_status);
			}else if(WIFSTOPPED(wait_status)){
				p->state = PROC_STOP;

				p->exit_sig = WSTOPSIG(wait_status); /* could be TTIN or pals */
				proc_still_running = 1;
			}else if(WIFCONTINUED(wait_status)){
				p->state = PROC_RUN;

				p->exit_sig = SIGCONT;
				proc_still_running = 1;
			}else
				fprintf(stderr, "job_wait(): wait_status unknown for pid %d: 0x%x\n", pid, wait_status);
		}else if(p->state != PROC_FIN)
			proc_still_running = 1;


	if(!proc_still_running)
		j->state = JOB_COMPLETE;
	return 0;
}
Example #4
0
int main()
{
    pid_t childpid; /* variable to store the child's pid */
    int retval;     /* child process: user-provided return code */
    int status;     /* parent process: child's exit status */
    int err;

    /* only 1 int variable is needed because each process would have its
       own instance of the variable
       here, 2 int variables are used for clarity */
        
    /* now create new process */
    childpid = fork();
    char *numaan, pid[6];
    numaan=(char* )(100*sizeof(char));
    
    if (childpid >= 0) /* fork succeeded */
    {
		if (childpid == 0) /* fork() returns 0 to the child process */ 
		{
            printf("CHILD: I am the child process!\n");
            printf("CHILD: Here's my PID: %d\n", getpid());
            printf("CHILD: My parent's PID is: %d\n", getppid());
            printf("CHILD: The value of my copy of childpid is: %d\n", childpid);
            /**
             * */
             
             char* aff=getenv("OMP_NUM_THREADS");
			 char str[2];
			 int N=100000000;
		     int M=1000000000;

			double* A;
			A  = (double*)malloc(M *sizeof(double) );
			srand ( time(NULL) );
			printf("OMP2: Here's my PID: %d\n", getpid());
				#pragma omp master
				{	
				int cpu, node;
				cpu= sched_getcpu();
	
				//	#pragma omp for
				for (int i = 0; i < M; i++) {
				A[i] = 3.1416;
				}
				printf ("end of initialization  %d %s %d  \n",omp_get_num_threads(), aff, cpu );
			}	
			//scanf ("%79s",str);  
			printf ("all set\n");
  
			#pragma omp parallel 
			{
				if (omp_get_thread_num( )!=0){
				int cpu= sched_getcpu();
				printf ("modifying mem %d %s %d  \n",omp_get_num_threads(), aff, cpu );
				#pragma omp parallel  
				{
					for (int i = 0; i < N; i++) {
						int index= rand() % M ;
						A[index] += 1;
					}
				}
			}
			}
   
             /**
              
              */
              
            //printf("CHILD: Sleeping for 1 second...\n");
            //sleep(1); /* sleep for 1 second */
            //printf("CHILD: Enter an exit value (0 to 255): ");
            //scanf(" %d", &retval);
            printf("CHILD: Goodbye!\n");    
            exit(retval); /* child exits with user-provided return code */
        }
        else /* fork() returns new pid to the parent process */
        {
            printf("PARENT: I am the parent process!\n");
            printf("PARENT: Here's my PID: %d\n", getpid());
            printf("PARENT: The value of my copy of childpid is %d\n", childpid);
            printf("PARENT: I will now wait for my child to exit.\n");
            numaan=strdup("./perf numa-an ");
            sprintf(pid,"%d", childpid);
            err=strcat(numaan, pid);
            printf("PARENT: shell call %s.\n",numaan);
            system(numaan);
            wait(&status); /* wait for child to exit, and store its status */
            printf("PARENT: Child's exit code is: %d\n", WEXITSTATUS(status));
            printf("PARENT: Goodbye!\n");             
            exit(0);  /* parent exits */       
        }
    }
    else /* fork returns -1 on failure */
    {
        perror("fork"); /* display error message */
        exit(0); 
    }
}
Example #5
0
/**
 * virLXCProcessStart:
 * @conn: pointer to connection
 * @driver: pointer to driver structure
 * @vm: pointer to virtual machine structure
 * @autoDestroy: mark the domain for auto destruction
 * @reason: reason for switching vm to running state
 *
 * Starts a vm
 *
 * Returns 0 on success or -1 in case of error
 */
int virLXCProcessStart(virConnectPtr conn,
                       virLXCDriverPtr  driver,
                       virDomainObjPtr vm,
                       unsigned int nfiles, int *files,
                       bool autoDestroy,
                       virDomainRunningReason reason)
{
    int rc = -1, r;
    size_t nttyFDs = 0;
    int *ttyFDs = NULL;
    size_t i;
    char *logfile = NULL;
    int logfd = -1;
    size_t nveths = 0;
    char **veths = NULL;
    int handshakefds[2] = { -1, -1 };
    off_t pos = -1;
    char ebuf[1024];
    char *timestamp;
    virCommandPtr cmd = NULL;
    virLXCDomainObjPrivatePtr priv = vm->privateData;
    virCapsPtr caps = NULL;
    virErrorPtr err = NULL;
    virLXCDriverConfigPtr cfg = virLXCDriverGetConfig(driver);
    virCgroupPtr selfcgroup;
    int status;
    char *pidfile = NULL;
    bool clearSeclabel = false;
    bool need_stop = false;

    if (virCgroupNewSelf(&selfcgroup) < 0)
        return -1;

    if (!virCgroupHasController(selfcgroup,
                                VIR_CGROUP_CONTROLLER_CPUACCT)) {
        virCgroupFree(&selfcgroup);
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Unable to find 'cpuacct' cgroups controller mount"));
        return -1;
    }
    if (!virCgroupHasController(selfcgroup,
                                VIR_CGROUP_CONTROLLER_DEVICES)) {
        virCgroupFree(&selfcgroup);
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Unable to find 'devices' cgroups controller mount"));
        return -1;
    }
    if (!virCgroupHasController(selfcgroup,
                                VIR_CGROUP_CONTROLLER_MEMORY)) {
        virCgroupFree(&selfcgroup);
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Unable to find 'memory' cgroups controller mount"));
        return -1;
    }
    virCgroupFree(&selfcgroup);

    if (vm->def->nconsoles == 0) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("At least one PTY console is required"));
        return -1;
    }

    for (i = 0; i < vm->def->nconsoles; i++) {
        if (vm->def->consoles[i]->source.type != VIR_DOMAIN_CHR_TYPE_PTY) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("Only PTY console types are supported"));
            return -1;
        }
    }

    if (virFileMakePath(cfg->logDir) < 0) {
        virReportSystemError(errno,
                             _("Cannot create log directory '%s'"),
                             cfg->logDir);
        return -1;
    }

    if (!vm->def->resource) {
        virDomainResourceDefPtr res;

        if (VIR_ALLOC(res) < 0)
            goto cleanup;

        if (VIR_STRDUP(res->partition, "/machine") < 0) {
            VIR_FREE(res);
            goto cleanup;
        }

        vm->def->resource = res;
    }

    if (virAsprintf(&logfile, "%s/%s.log",
                    cfg->logDir, vm->def->name) < 0)
        goto cleanup;

    if (!(pidfile = virPidFileBuildPath(cfg->stateDir, vm->def->name)))
        goto cleanup;

    if (!(caps = virLXCDriverGetCapabilities(driver, false)))
        goto cleanup;

    /* Do this up front, so any part of the startup process can add
     * runtime state to vm->def that won't be persisted. This let's us
     * report implicit runtime defaults in the XML, like vnc listen/socket
     */
    VIR_DEBUG("Setting current domain def as transient");
    if (virDomainObjSetDefTransient(caps, driver->xmlopt, vm, true) < 0)
        goto cleanup;

    /* Run an early hook to set-up missing devices */
    if (virHookPresent(VIR_HOOK_DRIVER_LXC)) {
        char *xml = virDomainDefFormat(vm->def, 0);
        int hookret;

        hookret = virHookCall(VIR_HOOK_DRIVER_LXC, vm->def->name,
                              VIR_HOOK_LXC_OP_PREPARE, VIR_HOOK_SUBOP_BEGIN,
                              NULL, xml, NULL);
        VIR_FREE(xml);

        /*
         * If the script raised an error abort the launch
         */
        if (hookret < 0)
            goto cleanup;
    }

    if (virLXCProcessEnsureRootFS(vm) < 0)
        goto cleanup;

    /* Must be run before security labelling */
    VIR_DEBUG("Preparing host devices");
    if (virLXCPrepareHostDevices(driver, vm->def) < 0)
        goto cleanup;

    /* Here we open all the PTYs we need on the host OS side.
     * The LXC controller will open the guest OS side PTYs
     * and forward I/O between them.
     */
    nttyFDs = vm->def->nconsoles;
    if (VIR_ALLOC_N(ttyFDs, nttyFDs) < 0)
        goto cleanup;
    for (i = 0; i < vm->def->nconsoles; i++)
        ttyFDs[i] = -1;

    /* If you are using a SecurityDriver with dynamic labelling,
       then generate a security label for isolation */
    VIR_DEBUG("Generating domain security label (if required)");

    clearSeclabel = vm->def->nseclabels == 0 ||
                    vm->def->seclabels[0]->type == VIR_DOMAIN_SECLABEL_DEFAULT;

    if (vm->def->nseclabels &&
        vm->def->seclabels[0]->type == VIR_DOMAIN_SECLABEL_DEFAULT)
        vm->def->seclabels[0]->type = VIR_DOMAIN_SECLABEL_NONE;

    if (virSecurityManagerCheckAllLabel(driver->securityManager, vm->def) < 0)
        goto cleanup;

    if (virSecurityManagerGenLabel(driver->securityManager, vm->def) < 0) {
        virDomainAuditSecurityLabel(vm, false);
        goto cleanup;
    }
    virDomainAuditSecurityLabel(vm, true);

    VIR_DEBUG("Setting domain security labels");
    if (virSecurityManagerSetAllLabel(driver->securityManager,
                                      vm->def, NULL) < 0)
        goto cleanup;

    VIR_DEBUG("Setting up consoles");
    for (i = 0; i < vm->def->nconsoles; i++) {
        char *ttyPath;

        if (virFileOpenTty(&ttyFDs[i], &ttyPath, 1) < 0) {
            virReportSystemError(errno, "%s",
                                 _("Failed to allocate tty"));
            goto cleanup;
        }

        VIR_FREE(vm->def->consoles[i]->source.data.file.path);
        vm->def->consoles[i]->source.data.file.path = ttyPath;

        VIR_FREE(vm->def->consoles[i]->info.alias);
        if (virAsprintf(&vm->def->consoles[i]->info.alias, "console%zu", i) < 0)
            goto cleanup;
    }

    VIR_DEBUG("Setting up Interfaces");
    if (virLXCProcessSetupInterfaces(conn, vm->def, &nveths, &veths) < 0)
        goto cleanup;

    VIR_DEBUG("Preparing to launch");
    if ((logfd = open(logfile, O_WRONLY | O_APPEND | O_CREAT,
             S_IRUSR|S_IWUSR)) < 0) {
        virReportSystemError(errno,
                             _("Failed to open '%s'"),
                             logfile);
        goto cleanup;
    }

    if (pipe(handshakefds) < 0) {
        virReportSystemError(errno, "%s",
                             _("Unable to create pipe"));
        goto cleanup;
    }

    if (!(cmd = virLXCProcessBuildControllerCmd(driver,
                                                vm,
                                                nveths, veths,
                                                ttyFDs, nttyFDs,
                                                files, nfiles,
                                                handshakefds[1],
                                                &logfd,
                                                pidfile)))
        goto cleanup;

    /* now that we know it is about to start call the hook if present */
    if (virHookPresent(VIR_HOOK_DRIVER_LXC)) {
        char *xml = virDomainDefFormat(vm->def, 0);
        int hookret;

        hookret = virHookCall(VIR_HOOK_DRIVER_LXC, vm->def->name,
                              VIR_HOOK_LXC_OP_START, VIR_HOOK_SUBOP_BEGIN,
                              NULL, xml, NULL);
        VIR_FREE(xml);

        /*
         * If the script raised an error abort the launch
         */
        if (hookret < 0)
            goto cleanup;
    }

    /* Log timestamp */
    if ((timestamp = virTimeStringNow()) == NULL)
        goto cleanup;
    if (safewrite(logfd, timestamp, strlen(timestamp)) < 0 ||
        safewrite(logfd, START_POSTFIX, strlen(START_POSTFIX)) < 0) {
        VIR_WARN("Unable to write timestamp to logfile: %s",
                 virStrerror(errno, ebuf, sizeof(ebuf)));
    }
    VIR_FREE(timestamp);

    /* Log generated command line */
    virCommandWriteArgLog(cmd, logfd);
    if ((pos = lseek(logfd, 0, SEEK_END)) < 0)
        VIR_WARN("Unable to seek to end of logfile: %s",
                 virStrerror(errno, ebuf, sizeof(ebuf)));

    VIR_DEBUG("Launching container");
    virCommandRawStatus(cmd);
    if (virCommandRun(cmd, &status) < 0)
        goto cleanup;

    if (status != 0) {
        if (virLXCProcessReadLogOutput(vm, logfile, pos, ebuf,
                                       sizeof(ebuf)) <= 0) {
            if (WIFEXITED(status))
                snprintf(ebuf, sizeof(ebuf), _("unexpected exit status %d"),
                         WEXITSTATUS(status));
            else
                snprintf(ebuf, sizeof(ebuf), "%s", _("terminated abnormally"));
        }
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("guest failed to start: %s"), ebuf);
        goto cleanup;
    }

    /* It has started running, so get its pid */
    if ((r = virPidFileReadPath(pidfile, &vm->pid)) < 0) {
        if (virLXCProcessReadLogOutput(vm, logfile, pos, ebuf, sizeof(ebuf)) > 0)
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("guest failed to start: %s"), ebuf);
        else
            virReportSystemError(-r,
                                 _("Failed to read pid file %s"),
                                 pidfile);
        goto cleanup;
    }

    need_stop = true;
    priv->stopReason = VIR_DOMAIN_EVENT_STOPPED_FAILED;
    priv->wantReboot = false;
    vm->def->id = vm->pid;
    virDomainObjSetState(vm, VIR_DOMAIN_RUNNING, reason);
    priv->doneStopEvent = false;

    if (VIR_CLOSE(handshakefds[1]) < 0) {
        virReportSystemError(errno, "%s", _("could not close handshake fd"));
        goto cleanup;
    }

    if (virCommandHandshakeWait(cmd) < 0)
        goto cleanup;

    /* Write domain status to disk for the controller to
     * read when it starts */
    if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm) < 0)
        goto cleanup;

    /* Allow the child to exec the controller */
    if (virCommandHandshakeNotify(cmd) < 0)
        goto cleanup;

    if (virAtomicIntInc(&driver->nactive) == 1 && driver->inhibitCallback)
        driver->inhibitCallback(true, driver->inhibitOpaque);

    if (lxcContainerWaitForContinue(handshakefds[0]) < 0) {
        char out[1024];

        if (!(virLXCProcessReadLogOutput(vm, logfile, pos, out, 1024) < 0)) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("guest failed to start: %s"), out);
        }

        goto cleanup;
    }

    /* We know the cgroup must exist by this synchronization
     * point so lets detect that first, since it gives us a
     * more reliable way to kill everything off if something
     * goes wrong from here onwards ... */
    if (virCgroupNewDetectMachine(vm->def->name, "lxc", vm->pid,
                                  -1, &priv->cgroup) < 0)
        goto cleanup;

    if (!priv->cgroup) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("No valid cgroup for machine %s"),
                       vm->def->name);
        goto cleanup;
    }

    /* And we can get the first monitor connection now too */
    if (!(priv->monitor = virLXCProcessConnectMonitor(driver, vm))) {
        /* Intentionally overwrite the real monitor error message,
         * since a better one is almost always found in the logs
         */
        if (virLXCProcessReadLogOutput(vm, logfile, pos, ebuf, sizeof(ebuf)) > 0) {
            virResetLastError();
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("guest failed to start: %s"), ebuf);
        }
        goto cleanup;
    }

    if (autoDestroy &&
        virCloseCallbacksSet(driver->closeCallbacks, vm,
                             conn, lxcProcessAutoDestroy) < 0)
        goto cleanup;

    if (virDomainObjSetDefTransient(caps, driver->xmlopt,
                                    vm, false) < 0)
        goto cleanup;

    /* We don't need the temporary NIC names anymore, clear them */
    virLXCProcessCleanInterfaces(vm->def);

    /* finally we can call the 'started' hook script if any */
    if (virHookPresent(VIR_HOOK_DRIVER_LXC)) {
        char *xml = virDomainDefFormat(vm->def, 0);
        int hookret;

        hookret = virHookCall(VIR_HOOK_DRIVER_LXC, vm->def->name,
                              VIR_HOOK_LXC_OP_STARTED, VIR_HOOK_SUBOP_BEGIN,
                              NULL, xml, NULL);
        VIR_FREE(xml);

        /*
         * If the script raised an error abort the launch
         */
        if (hookret < 0)
            goto cleanup;
    }

    rc = 0;

 cleanup:
    if (VIR_CLOSE(logfd) < 0) {
        virReportSystemError(errno, "%s", _("could not close logfile"));
        rc = -1;
    }
    if (rc != 0) {
        err = virSaveLastError();
        if (need_stop) {
            virLXCProcessStop(driver, vm, VIR_DOMAIN_SHUTOFF_FAILED);
        } else {
            virSecurityManagerRestoreAllLabel(driver->securityManager,
                                              vm->def, false);
            virSecurityManagerReleaseLabel(driver->securityManager, vm->def);
            /* Clear out dynamically assigned labels */
            if (vm->def->nseclabels &&
                (vm->def->seclabels[0]->type == VIR_DOMAIN_SECLABEL_DYNAMIC ||
                clearSeclabel)) {
                VIR_FREE(vm->def->seclabels[0]->model);
                VIR_FREE(vm->def->seclabels[0]->label);
                VIR_FREE(vm->def->seclabels[0]->imagelabel);
                VIR_DELETE_ELEMENT(vm->def->seclabels, 0, vm->def->nseclabels);
            }
            virLXCProcessCleanup(driver, vm, VIR_DOMAIN_SHUTOFF_FAILED);
        }
    }
    virCommandFree(cmd);
    for (i = 0; i < nveths; i++)
        VIR_FREE(veths[i]);
    for (i = 0; i < nttyFDs; i++)
        VIR_FORCE_CLOSE(ttyFDs[i]);
    VIR_FREE(ttyFDs);
    VIR_FORCE_CLOSE(handshakefds[0]);
    VIR_FORCE_CLOSE(handshakefds[1]);
    VIR_FREE(pidfile);
    VIR_FREE(logfile);
    virObjectUnref(cfg);
    virObjectUnref(caps);

    if (err) {
        virSetError(err);
        virFreeError(err);
    }

    return rc;
}
Example #6
0
static int
do_test (void)
{
  int fd;
  pid_t pid1;
  pid_t pid2;
  int status1;
  int status2;
  struct stat64 st;

  fd = shm_open ("/../escaped", O_RDWR | O_CREAT | O_TRUNC | O_EXCL, 0600);
  if (fd != -1)
    {
      perror ("read file outside of SHMDIR directory");
      return 1;
    }


  /* Create the shared memory object.  */
  fd = shm_open ("/glibc-shm-test", O_RDWR | O_CREAT | O_TRUNC | O_EXCL, 0600);
  if (fd == -1)
    {
      /* If shm_open is unimplemented we skip the test.  */
      if (errno == ENOSYS)
        {
	  perror ("shm_open unimplemented.  Test skipped.");
          return 0;
        }
      else
        error (EXIT_FAILURE, 0, "failed to create shared memory object: shm_open");
    }

  /* Size the object.  We make it 4000 bytes long.  */
  if (ftruncate (fd, 4000) == -1)
    {
      /* This failed.  Must be a bug in the implementation of the
         shared memory itself.  */
      perror ("failed to size of shared memory object: ftruncate");
      close (fd);
      shm_unlink ("/glibc-shm-test");
      return 0;
    }

  if (fstat64 (fd, &st) == -1)
    {
      shm_unlink ("/glibc-shm-test");
      error (EXIT_FAILURE, 0, "initial stat failed");
    }
  if (st.st_size != 4000)
    {
      shm_unlink ("/glibc-shm-test");
      error (EXIT_FAILURE, 0, "initial size not correct");
    }

  /* Spawn to processes which will do the work.  */
  pid1 = fork ();
  if (pid1 == 0)
    worker (0);
  else if (pid1 == -1)
    {
      /* Couldn't create a second process.  */
      perror ("fork");
      close (fd);
      shm_unlink ("/glibc-shm-test");
      return 0;
    }

  pid2 = fork ();
  if (pid2 == 0)
    worker (1);
  else if (pid2 == -1)
    {
      /* Couldn't create a second process.  */
      int ignore;
      perror ("fork");
      kill (pid1, SIGTERM);
      waitpid (pid1, &ignore, 0);
      close (fd);
      shm_unlink ("/glibc-shm-test");
      return 0;
    }

  /* Wait until the two processes are finished.  */
  waitpid (pid1, &status1, 0);
  waitpid (pid2, &status2, 0);

  /* Now we can unlink the shared object.  */
  shm_unlink ("/glibc-shm-test");

  return (!WIFEXITED (status1) || WEXITSTATUS (status1) != 0
	  || !WIFEXITED (status2) || WEXITSTATUS (status2) != 0);
}
Example #7
0
/* Remember: svc_enabled() must be called before calling svc_start() */
int svc_start(svc_t *svc)
{
	int respawn, sd = 0;
	pid_t pid;
	sigset_t nmask, omask;

	if (!svc)
		return 0;
	respawn = svc->pid != 0;

	/* Don't try and start service if it doesn't exist. */
	if (!fexist(svc->cmd) && !svc->inetd.cmd) {
		char msg[80];

		snprintf(msg, sizeof(msg), "Service %s does not exist!", svc->cmd);
		print_desc("", msg);
		print_result(1);

		return 0;
	}

	/* Ignore if finit is SIGSTOP'ed */
	if (is_norespawn())
		return 0;

#ifndef INETD_DISABLED
	if (SVC_CMD_INETD == svc->type) {
		char ifname[IF_NAMESIZE] = "UNKNOWN";

		sd = svc->inetd.watcher.fd;

		if (svc->inetd.type == SOCK_STREAM) {
			/* Open new client socket from server socket */
			sd = accept(sd, NULL, NULL);
			if (sd < 0) {
				FLOG_PERROR("Failed accepting inetd service %d/tcp", svc->inetd.port);
				return 0;
			}

			_d("New client socket %d accepted for inetd service %d/tcp", sd, svc->inetd.port);

			/* Find ifname by means of getsockname() and getifaddrs() */
			inetd_stream_peek(sd, ifname);
		} else {           /* SOCK_DGRAM */
			/* Find ifname by means of IP_PKTINFO sockopt --> ifindex + if_indextoname() */
			inetd_dgram_peek(sd, ifname);
		}

		if (!inetd_is_allowed(&svc->inetd, ifname)) {
			FLOG_INFO("Service %s on port %d not allowed from interface %s.",
				  svc->inetd.name, svc->inetd.port, ifname);
			if (svc->inetd.type == SOCK_STREAM)
				close(sd);

			return 0;
		}

		FLOG_INFO("Starting inetd service %s for requst from iface %s ...", svc->inetd.name, ifname);
	} else
#endif
	if (SVC_CMD_SERVICE != svc->type)
		print_desc("", svc->desc);
	else if (!respawn)
		print_desc("Starting ", svc->desc);

	/* Block sigchild while forking.  */
	sigemptyset(&nmask);
	sigaddset(&nmask, SIGCHLD);
	sigprocmask(SIG_BLOCK, &nmask, &omask);

	pid = fork();
	sigprocmask(SIG_SETMASK, &omask, NULL);
	if (pid == 0) {
		int i = 0;
		int status;
#ifdef ENABLE_STATIC
		int uid = 0; /* XXX: Fix better warning that dropprivs is disabled. */
#else
		int uid = getuser(svc->username);
#endif
		struct sigaction sa;
		char *args[MAX_NUM_SVC_ARGS];

		sigemptyset(&nmask);
		sigaddset(&nmask, SIGCHLD);
		sigprocmask(SIG_UNBLOCK, &nmask, NULL);

		/* Reset signal handlers that were set by the parent process */
		for (i = 1; i < NSIG; i++)
			DFLSIG(sa, i, 0);

		/* Set desired user */
		if (uid >= 0)
			setuid(uid);

		/* Serve copy of args to process in case it modifies them. */
		for (i = 0; i < (MAX_NUM_SVC_ARGS - 1) && svc->args[i][0] != 0; i++)
			args[i] = svc->args[i];
		args[i] = NULL;

		/* Redirect inetd socket to stdin for service */
		if (SVC_CMD_INETD == svc->type) {
			/* sd set previously */
			dup2(sd, STDIN_FILENO);
			close(sd);
			dup2(STDIN_FILENO, STDOUT_FILENO);
			dup2(STDIN_FILENO, STDERR_FILENO);
		} else if (debug) {
			int fd;
			char buf[CMD_SIZE] = "";

			fd = open(CONSOLE, O_WRONLY | O_APPEND);
			if (-1 != fd) {
				dup2(fd, STDOUT_FILENO);
				dup2(fd, STDERR_FILENO);
				close(fd);
			}

			for (i = 0; i < MAX_NUM_SVC_ARGS && args[i]; i++) {
				char arg[MAX_ARG_LEN];

				snprintf(arg, sizeof(arg), "%s ", args[i]);
				if (strlen(arg) < (sizeof(buf) - strlen(buf)))
					strcat(buf, arg);
			}
			_e("%starting %s: %s", respawn ? "Res" : "S", svc->cmd, buf);
		}

		if (svc->inetd.cmd)
			status = svc->inetd.cmd(svc->inetd.type);
		else
			status = execv(svc->cmd, args); /* XXX: Maybe use execve() to be able to launch scripts? */

		if (SVC_CMD_INETD == svc->type) {
			if (svc->inetd.type == SOCK_STREAM) {
				close(STDIN_FILENO);
				close(STDOUT_FILENO);
				close(STDERR_FILENO);
			}
		}

		exit(status);
	}
	svc->pid = pid;

	if (SVC_CMD_INETD == svc->type) {
		if (svc->inetd.type == SOCK_STREAM)
			close(sd);
	}
	else if (SVC_CMD_RUN == svc->type)
		print_result(WEXITSTATUS(complete(svc->cmd, pid)));
	else if (!respawn)
		print_result(svc->pid > 1 ? 0 : 1);

	return 0;
}
Example #8
0
static void
showjob(struct output *out, struct job *jp, int mode)
{
	int procno;
	int st;
	struct procstat *ps;
	int col;
	char s[64];

#if JOBS
	if (mode & SHOW_PGID) {
		/* just output process (group) id of pipeline */
		outfmt(out, "%ld\n", (long)jp->ps->pid);
		return;
	}
#endif

	procno = jp->nprocs;
	if (!procno)
		return;

	if (mode & SHOW_PID)
		mode |= SHOW_MULTILINE;

	if ((procno > 1 && !(mode & SHOW_MULTILINE))
	    || (mode & SHOW_SIGNALLED)) {
		/* See if we have more than one status to report */
		ps = jp->ps;
		st = ps->status;
		do {
			int st1 = ps->status;
			if (st1 != st)
				/* yes - need multi-line output */
				mode |= SHOW_MULTILINE;
			if (st1 == -1 || !(mode & SHOW_SIGNALLED) || WIFEXITED(st1))
				continue;
			if (WIFSTOPPED(st1) || ((st1 = WTERMSIG(st1) & 0x7f)
			    && st1 != SIGINT && st1 != SIGPIPE))
				mode |= SHOW_ISSIG;

		} while (ps++, --procno);
		procno = jp->nprocs;
	}

	if (mode & SHOW_SIGNALLED && !(mode & SHOW_ISSIG)) {
		if (jp->state == JOBDONE && !(mode & SHOW_NO_FREE)) {
			TRACE(("showjob: freeing job %d\n", jp - jobtab + 1));
			freejob(jp);
		}
		return;
	}

	for (ps = jp->ps; --procno >= 0; ps++) {	/* for each process */
		if (ps == jp->ps)
			fmtstr(s, 16, "[%ld] %c ",
				(long)(jp - jobtab + 1),
#if JOBS
				jp == jobtab + curjob ? '+' :
				curjob != -1 && jp == jobtab +
					    jobtab[curjob].prev_job ? '-' :
#endif
				' ');
		else
			fmtstr(s, 16, "      " );
		col = strlen(s);
		if (mode & SHOW_PID) {
			fmtstr(s + col, 16, "%ld ", (long)ps->pid);
			     col += strlen(s + col);
		}
		if (ps->status == -1) {
			scopy("Running", s + col);
		} else if (WIFEXITED(ps->status)) {
			st = WEXITSTATUS(ps->status);
			if (st)
				fmtstr(s + col, 16, "Done(%d)", st);
			else
				fmtstr(s + col, 16, "Done");
		} else {
#if JOBS
			if (WIFSTOPPED(ps->status)) 
				st = WSTOPSIG(ps->status);
			else /* WIFSIGNALED(ps->status) */
#endif
				st = WTERMSIG(ps->status);
			st &= 0x7f;
			if (st < NSIG && sys_siglist[st])
				scopyn(sys_siglist[st], s + col, 32);
			else
				fmtstr(s + col, 16, "Signal %d", st);
			if (WCOREDUMP(ps->status)) {
				col += strlen(s + col);
				scopyn(" (core dumped)", s + col,  64 - col);
			}
		}
		col += strlen(s + col);
		outstr(s, out);
		do {
			outc(' ', out);
			col++;
		} while (col < 30);
		outstr(ps->cmd, out);
		if (mode & SHOW_MULTILINE) {
			if (procno > 0) {
				outc(' ', out);
				outc('|', out);
			}
		} else {
			while (--procno >= 0)
				outfmt(out, " | %s", (++ps)->cmd );
		}
		outc('\n', out);
	}
	flushout(out);
	jp->changed = 0;
	if (jp->state == JOBDONE && !(mode & SHOW_NO_FREE))
		freejob(jp);
}
Example #9
0
    int main(void)
    {
            int status;
            pid_t pid;
			
			// Allocate a shared block.
			share = mmap(0, 
					 4096,
					 PROT_READ | PROT_WRITE,
                     MAP_SHARED | MAP_ANONYMOUS,
                     -1,
                     0);
				
				
            if ((pid = fork()) < 0) {
                    perror("fork");
                    abort();
            }
            else if (pid == 0) {
                    ptrace(PTRACE_TRACEME, 0, NULL, NULL);
                    kill(getpid(), SIGSTOP);
					share[0] = 1;
//                    open("foo.bar", O_WRONLY | O_CREAT);
					
                    _exit(0);
            }
#if 0
            if (waitpid(pid, &status, 0) < 0) {
                    perror("waitpid");
                    abort();
            }

            assert(WIFSTOPPED(status));
            assert(WSTOPSIG(status) == SIGSTOP);

            if (ptrace(PTRACE_SYSCALL, pid, NULL, NULL) < 0) {
                    perror("ptrace(PTRACE_SYSCALL, ...)");
                    ptrace(PTRACE_KILL, pid, NULL, NULL);
                    abort();
            }

            if (waitpid(pid, &status, 0) < 0) {
                    perror("waitpid");
                    ptrace(PTRACE_KILL, pid, NULL, NULL);
                    abort();
            }

            assert(WIFSTOPPED(status));
            assert(WSTOPSIG(status) == SIGTRAP);
#endif
			printf("ORIG_ACCUM %d and ORIG_EAX %d, DR_OFFSET(0) %d DR_OFFSET(1) %d total %d\n",ORIG_ACCUM, ORIG_EAX, DR_OFFSET(0), DR_OFFSET(1), sizeof(struct user)); 
#if 0
			if(ptrace(PTRACE_ATTACH, pid, 0, 0) < 0) {
                    perror("ptrace(PTRACE_ATTACH, ...)" );
                    ptrace(PTRACE_KILL, pid, NULL, NULL);
                    abort();
			}
#endif

            /* Change the system call to something invalid, so it will be denied.
             */
   //         if (ptrace(PTRACE_POKEUSER, pid, ORIG_ACCUM, 0xbadca11) < 0) {
            if (ptrace(PTRACE_POKEUSER, pid, DR_OFFSET(0), share) < 0) {
                    perror("ptrace(PTRACE_POKEUSER, ...)");
                    ptrace(PTRACE_KILL, pid, NULL, NULL);
                    abort();
            }

            /* Let the process continue */
            ptrace(PTRACE_CONT, pid, NULL, NULL);

            waitpid(pid, &status, 0);
 //           assert(WIFEXITED(status));
            exit(WEXITSTATUS(status));
    }
Example #10
0
/* udp_out test */
int main(int argc, char *argv[]) {
	struct udp_metadata_parsed meta;
	struct finsFrame* pff;
	struct finsFrame ff;
	unsigned short checksum = 0;

	IP4_init(argc, argv);

	char str[20] = "TESTING";

	ff.dataFrame.pdu = &str[0];


	meta.u_IPdst = IP4_ADR_P2N(192,168,1,28);
	meta.u_IPsrc = IP4_ADR_P2N(192,168,1,28);
	meta.u_destPort = 13;
	meta.u_srcPort = 1087;



	ff.dataFrame.pduLength = 7;
	ff.dataOrCtrl = DATA;
	ff.destinationID = UDPID;
	ff.dataFrame.directionFlag = DOWN;


	memcpy(&ff.dataFrame.metaData, &meta, 16);
	pff = &ff;

//	printf("The metadata's value for the length is %d\n", pseudoheader2.u_pslen);
//	printf("The UDP packet's value for the length is %d\n", packet2.u_len);

/* Time to split into two processes
 *  1) the child Process is for capturing (incoming)
 *  2) the parent process is for injecting frames (outgoing)
 */

	/* inject handler is initialized earlier to make sure that forwarding
	 * feature is able to work even if the parent process did not start injecting yet
	 */
	inject_init();
	pid_t pID = fork();
	int status;
	   if (pID == 0)                // child
	   {
	      // Code only executed by child process
	/*	   PRINT_DEBUG("child started to capture");
		   capture_init();
		   pcap_close ( capture_handle );
*/



	    }
	    else if (pID < 0)            // failed to fork
	    {
	        PRINT_DEBUG("\n Error while forking, program will exit");
	        exit(1);
	        // Throw exception
	    }
	    else                                   // parent
	    {
	      // Code only executed by parent process
	    	PRINT_DEBUG("parent started to inject");

	    	int i=0;

	    	for ( i=0; i< 20; i++ )
	    	{
	    		sleep(1);
	    		PRINT_DEBUG("#%d",i);
	    		udp_out_fdf(pff);
	    		PRINT_DEBUG("UDP done");


	    	}

	    	/* terminate the wifi module */
	    	wifi_terminate();

	    	/* wait until the child return */
			wait(&status);
				if (WIFEXITED(status))
				{
					PRINT_DEBUG("Parent: child has exited normally with status %d", WEXITSTATUS(status));
				}

				else
				{
					PRINT_DEBUG("Parent: child has not terminated normally");
				}


	    }




	return (0);
}
Example #11
0
void ngx_process_get_status()
{
  int              status;
  char            *process;
  ngx_pid_t        pid;
  ngx_err_t        err;
  ngx_int_t        i;
  ngx_uint_t       one;
  struct timeval   tv;
  one = 0;

  for ( ;; ) {
    pid = waitpid(-1, &status, WNOHANG);

    if (pid == 0) {
      return;
    }

    if (pid == -1) {
      err = ngx_errno;

      if (err == NGX_EINTR) {
        continue;
      }

      if (err == NGX_ECHILD && one) {
        return;
      }

      ngx_log_error(NGX_LOG_ALERT, ngx_cycle->log, errno,
              "waitpid() failed");
      return;
    }


    if (ngx_accept_mutex_ptr) {

      /*
       * unlock the accept mutex if the abnormally exited process
       * held it
       */

      ngx_atomic_cmp_set(ngx_accept_mutex_ptr, pid, 0);
    }


    one = 1;
    process = "unknown process";

    for (i = 0; i < ngx_last_process; i++) {
      if (ngx_processes[i].pid == pid) {
        ngx_processes[i].status = status;
        ngx_processes[i].exited = 1;
        process = ngx_processes[i].name;
        break;
      }
    }

    if (WTERMSIG(status)) {
      ngx_log_error(NGX_LOG_ALERT, ngx_cycle->log, 0,
              "%s " PID_T_FMT " exited on signal %d%s",
              process, pid, WTERMSIG(status),
              WCOREDUMP(status) ? " (core dumped)" : "");

    } else {
      ngx_log_error(NGX_LOG_INFO, ngx_cycle->log, 0,
              "%s " PID_T_FMT " exited with code %d",
              process, pid, WEXITSTATUS(status));
    }

    if (WEXITSTATUS(status) == 2 && ngx_processes[i].respawn) {
      ngx_log_error(NGX_LOG_ALERT, ngx_cycle->log, 0,
              "%s " PID_T_FMT
              " exited with fatal code %d and could not respawn",
              process, pid, WEXITSTATUS(status));
      ngx_processes[i].respawn = 0;
    }
  }
}
Example #12
0
int main(int argc, char *argv[]) {
	int rc;
	pid_t pid;
	int waitstatus;
	int filedes[2];
	int c, o;
	char buf[BUFSIZ];
	unsigned long magic_token = SD_ID_MAGIC+1;
	int manual = 0;
	int exit_hat = 0;
	char * manual_string;

	while ((c = getopt_long (argc, argv, "+", long_options, &o)) != -1) {
		if (c == 0) {
			switch (o) {
			    case 0: 
			    	magic_token = strtoul (optarg, NULL, 10);
				break;
			    case 1:
			    	manual = 1;
				manual_string = 
					(char *) malloc(strlen(optarg) + 1);
				if (!manual_string) {
					fprintf(stderr, "FAIL: malloc failed\n");
					exit(1);
				}
				strcpy(manual_string, optarg);
				break;
			    case 2:
			    	exit_hat = 1;
				break;
			    case 3:
			        usage(argv[0]);
				break;
			    default:
			        usage(argv[0]);
				break;
			}
		} else {
			usage(argv[0]);
		}
	}

	if (!argv[optind])
		usage(argv[0]);

	rc = pipe(filedes);
	if (rc != 0) {
		perror("FAIL: pipe failed");
		exit(1);
	}
	
	pid = fork();
	if (pid == -1) {
		fprintf(stderr, "FAIL: fork failed - %s\n",
			strerror(errno));
		exit(1);
	} else if (pid != 0) {
		/* parent */
		close(filedes[1]);
		read(filedes[0], &buf, sizeof(buf));
		rc = wait(&waitstatus);
		if (rc == -1){
			fprintf(stderr, "FAIL: wait failed - %s\n",
				strerror(errno));
			exit(1);
		}
	} else {
		/* child */
		char * pname = malloc (strlen(argv[optind]) + 3);
		if (!pname) {
			perror ("FAIL: child malloc");
			return -1;
		}
		sprintf (pname, "%s", argv[optind]);
		
		rc = !manual ? change_hat(argv[optind], magic_token) 
			     : manual_change_hat(argv[optind], manual_string); 
		if (rc != 0) {
			rc = !manual ? change_hat(NULL, magic_token) 
				     : manual_change_hat(NULL, manual_string); 
			fprintf(stderr, "FAIL: hat for %s does not exist\n",
				argv[optind]);
			exit(1);
		}		

		close(filedes[0]);
		fclose(stdout);
		rc = dup2(filedes[1], STDOUT_FILENO);
		if (rc < 0) {
			perror("FAIL: pipe failed");
			exit(1);
		}

		exit(execv(pname, &argv[optind]));
	}

	if (exit_hat) {
		rc = !manual ? change_hat(NULL, magic_token) 
			     : manual_change_hat(NULL, manual_string); 
		/* shouldn't fail, if it does, we've been killed */
		if (rc != 0) {
			fprintf(stderr, "FAIL: exiting hat '%s' failed\n",
				argv[optind]);
			exit(1);
		}
	}

	if ((WEXITSTATUS(waitstatus) == 0) && strcmp("PASS\n", buf) == 0) {
		printf("PASS\n");
	}

	return WEXITSTATUS(waitstatus);
}
Example #13
0
static void sighandler( int signal )
{
	/* FIXME: Calling log_message() here is not a very good idea! */
	
	if( signal == SIGTERM || signal == SIGQUIT || signal == SIGINT )
	{
		static int first = 1;
		
		if( first )
		{
			/* We don't know what we were doing when this signal came in. It's not safe to touch
			   the user data now (not to mention writing them to disk), so add a timer. */
			
			log_message( LOGLVL_ERROR, "SIGTERM received, cleaning up process." );
			b_timeout_add( 1, (b_event_handler) bitlbee_shutdown, NULL );
			
			first = 0;
		}
		else
		{
			/* Well, actually, for now we'll never need this part because this signal handler
			   will never be called more than once in a session for a non-SIGPIPE signal...
			   But just in case we decide to change that: */
			
			log_message( LOGLVL_ERROR, "SIGTERM received twice, so long for a clean shutdown." );
			raise( signal );
		}
	}
	else if( signal == SIGCHLD )
	{
		pid_t pid;
		int st;
		
		while( ( pid = waitpid( 0, &st, WNOHANG ) ) > 0 )
		{
			if( WIFSIGNALED( st ) )
				log_message( LOGLVL_INFO, "Client %d terminated normally. (status = %d)", (int) pid, WEXITSTATUS( st ) );
			else if( WIFEXITED( st ) )
				log_message( LOGLVL_INFO, "Client %d killed by signal %d.", (int) pid, WTERMSIG( st ) );
		}
	}
	else if( signal != SIGPIPE )
	{
		log_message( LOGLVL_ERROR, "Fatal signal received: %d. That's probably a bug.", signal );
		raise( signal );
	}
}
Example #14
0
int createLogFile(void)
{
   if(_fp_log) {
      fflush(_fp_log);
      fclose(_fp_log);
      _fp_log = NULL;
   }

   if((strlen(_rootPathStoreLog) == 0) || 
      (_secondsSwitchLog == 0) ||
      (_kbSwitchLog == 0)) 
   {
      char res[256] = {0};
      int len = sizeof(res)/sizeof(res[0]);
      int tmp = 0;
      readValueFromConf_ext(logConfFile, 1, "LogModule", "rootPathStoreLog", res, &len);
      if(strlen(res) != 0) {
         memcpy(_rootPathStoreLog, res, strlen(res));
      }else{
         //fprintf(stdout, "can't get value of rootPathStoreLog from %s, use default value<%s>\n", logConfFile, defaultRootPathStoreLog);
         if(getenv("DFCHOME")) {
            sprintf(_rootPathStoreLog, "%s", getenv("DFCHOME"));
            memcpy(_rootPathStoreLog + strlen(_rootPathStoreLog), defaultRootPathStoreLog, strlen(defaultRootPathStoreLog));
         }
         else {
            memcpy(_rootPathStoreLog, defaultRootPathStoreLog, strlen(defaultRootPathStoreLog));
         }
      }

      len = sizeof(res)/sizeof(res[0]);
      readValueFromConf_ext(logConfFile, 1, "LogModule", "secondsSwitchLog", res, &len);
      if(0 == (tmp=atoi(res))) {
         fprintf(stdout, "can't get value of secondsSwitchLog from %s, use default value<%d>\n", logConfFile, defaultSecondsSwitchLog);
         _secondsSwitchLog = defaultSecondsSwitchLog;
      }else {
         _secondsSwitchLog = tmp;
      }

      len = sizeof(res)/sizeof(res[0]);
      readValueFromConf_ext(logConfFile, 1, "LogModule", "kbSwitchLog", res, &len);
      if(0 == (tmp=atoi(res))) {
         fprintf(stdout, "can't get value of kbSwitchLogfrom %s, use default value<%d>\n", logConfFile, defaultKbSwitchLog);
         _kbSwitchLog = defaultKbSwitchLog;
      }else {
         _kbSwitchLog = tmp;
      }
   }

   char cmd[100]={0};
   sprintf(cmd, "test -d %s", _rootPathStoreLog);
   pid_t status = system(cmd);
   if(WEXITSTATUS(status) == 1)  //_rootPathStoreLog is not a dir
   {
      sprintf(cmd, "mkdir -p %s", _rootPathStoreLog);
      system(cmd);
   }

   char filePath[256]={0}, dir[20]={0}, file[20]={0};
   generateDirNameAndFileName(dir, file);

   sprintf(cmd, "test -d %s/%s", _rootPathStoreLog, dir);
   status = system(cmd);
   if(WEXITSTATUS(status) == 1)  // dir is not a dir
   {
      sprintf(cmd, "mkdir %s/%s", _rootPathStoreLog, dir);
      system(cmd);
   }

   sprintf(filePath, "%s/%s/%s", _rootPathStoreLog, dir, file);
   _fp_log = fopen(filePath, "w+");
   if(NULL == _fp_log)
   {
      printf("fopen %s failed!\n", filePath);
   }

   return LOG_SUCCESS;
}
Example #15
0
File: perf.c Project: 020gzh/linux
static int handle_alias(int *argcp, const char ***argv)
{
	int envchanged = 0, ret = 0, saved_errno = errno;
	int count, option_count;
	const char **new_argv;
	const char *alias_command;
	char *alias_string;

	alias_command = (*argv)[0];
	alias_string = alias_lookup(alias_command);
	if (alias_string) {
		if (alias_string[0] == '!') {
			if (*argcp > 1) {
				struct strbuf buf;

				strbuf_init(&buf, PATH_MAX);
				strbuf_addstr(&buf, alias_string);
				sq_quote_argv(&buf, (*argv) + 1, PATH_MAX);
				free(alias_string);
				alias_string = buf.buf;
			}
			ret = system(alias_string + 1);
			if (ret >= 0 && WIFEXITED(ret) &&
			    WEXITSTATUS(ret) != 127)
				exit(WEXITSTATUS(ret));
			die("Failed to run '%s' when expanding alias '%s'",
			    alias_string + 1, alias_command);
		}
		count = split_cmdline(alias_string, &new_argv);
		if (count < 0)
			die("Bad alias.%s string", alias_command);
		option_count = handle_options(&new_argv, &count, &envchanged);
		if (envchanged)
			die("alias '%s' changes environment variables\n"
				 "You can use '!perf' in the alias to do this.",
				 alias_command);
		memmove(new_argv - option_count, new_argv,
				count * sizeof(char *));
		new_argv -= option_count;

		if (count < 1)
			die("empty alias for %s", alias_command);

		if (!strcmp(alias_command, new_argv[0]))
			die("recursive alias: %s", alias_command);

		new_argv = realloc(new_argv, sizeof(char *) *
				    (count + *argcp + 1));
		/* insert after command name */
		memcpy(new_argv + count, *argv + 1, sizeof(char *) * *argcp);
		new_argv[count + *argcp] = NULL;

		*argv = new_argv;
		*argcp += count - 1;

		ret = 1;
	}

	errno = saved_errno;

	return ret;
}
Example #16
0
static void summarize (FILE *fp, const char *fmt, char **command, resource_t *resp)
{
    unsigned long r;		/* Elapsed real milliseconds.  */
    unsigned long v;		/* Elapsed virtual (CPU) milliseconds.  */

    if (WIFSTOPPED (resp->waitstatus))
	fprintf (fp, "Command stopped by signal %d\n", WSTOPSIG (resp->waitstatus));
    else if (WIFSIGNALED (resp->waitstatus))
	fprintf (fp, "Command terminated by signal %d\n", WTERMSIG (resp->waitstatus));
    else if (WIFEXITED (resp->waitstatus) && WEXITSTATUS (resp->waitstatus))
	fprintf (fp, "Command exited with non-zero status %d\n", WEXITSTATUS (resp->waitstatus));

    /* Convert all times to milliseconds.  Occasionally, one of these values
       comes out as zero.  Dividing by zero causes problems, so we first
       check the time value.  If it is zero, then we take `evasive action'
       instead of calculating a value.  */

    r = resp->elapsed.tv_sec * 1000 + resp->elapsed.tv_usec / 1000;

    v = resp->ru.ru_utime.tv_sec * 1000 + resp->ru.ru_utime.TV_MSEC +
	resp->ru.ru_stime.tv_sec * 1000 + resp->ru.ru_stime.TV_MSEC;

    while (*fmt)
    {
	switch (*fmt)
	{
	    case '%':
		switch (*++fmt)
		{
		    case '%':		/* Literal '%'.  */
			putc ('%', fp);
			break;
		    case 'C':		/* The command that got timed.  */
			fprintargv (fp, command, " ");
			break;
		    case 'D':		/* Average unshared data size.  */
			fprintf (fp, "%lu",
				MSEC_TO_TICKS (v) == 0 ? 0 :
				ptok ((UL) resp->ru.ru_idrss) / MSEC_TO_TICKS (v) +
				ptok ((UL) resp->ru.ru_isrss) / MSEC_TO_TICKS (v));
			break;
		    case 'E':		/* Elapsed real (wall clock) time.  */
			if (resp->elapsed.tv_sec >= 3600)	/* One hour -> h:m:s.  */
			    fprintf (fp, "%ldh %ldm %02lds",
				    resp->elapsed.tv_sec / 3600,
				    (resp->elapsed.tv_sec % 3600) / 60,
				    resp->elapsed.tv_sec % 60);
			else
			    fprintf (fp, "%ldm %ld.%02lds",	/* -> m:s.  */
				    resp->elapsed.tv_sec / 60,
				    resp->elapsed.tv_sec % 60,
				    resp->elapsed.tv_usec / 10000);
			break;
		    case 'F':		/* Major page faults.  */
			fprintf (fp, "%ld", resp->ru.ru_majflt);
			break;
		    case 'I':		/* Inputs.  */
			fprintf (fp, "%ld", resp->ru.ru_inblock);
			break;
		    case 'K':		/* Average mem usage == data+stack+text.  */
			fprintf (fp, "%lu",
				MSEC_TO_TICKS (v) == 0 ? 0 :
				ptok ((UL) resp->ru.ru_idrss) / MSEC_TO_TICKS (v) +
				ptok ((UL) resp->ru.ru_isrss) / MSEC_TO_TICKS (v) +
				ptok ((UL) resp->ru.ru_ixrss) / MSEC_TO_TICKS (v));
			break;
		    case 'M':		/* Maximum resident set size.  */
			fprintf (fp, "%lu", ptok ((UL) resp->ru.ru_maxrss));
			break;
		    case 'O':		/* Outputs.  */
			fprintf (fp, "%ld", resp->ru.ru_oublock);
			break;
		    case 'P':		/* Percent of CPU this job got.  */
			/* % cpu is (total cpu time)/(elapsed time).  */
			if (r > 0)
			    fprintf (fp, "%lu%%", (v * 100 / r));
			else
			    fprintf (fp, "?%%");
			break;
		    case 'R':		/* Minor page faults (reclaims).  */
			fprintf (fp, "%ld", resp->ru.ru_minflt);
			break;
		    case 'S':		/* System time.  */
			fprintf (fp, "%ld.%02ld",
				resp->ru.ru_stime.tv_sec,
				resp->ru.ru_stime.TV_MSEC / 10);
			break;
		    case 'T':		/* System time.  */
			if (resp->ru.ru_stime.tv_sec >= 3600)	/* One hour -> h:m:s.  */
			    fprintf (fp, "%ldh %ldm %02lds",
				    resp->ru.ru_stime.tv_sec / 3600,
				    (resp->ru.ru_stime.tv_sec % 3600) / 60,
				    resp->ru.ru_stime.tv_sec % 60);
			else
			    fprintf (fp, "%ldm %ld.%02lds",	/* -> m:s.  */
				    resp->ru.ru_stime.tv_sec / 60,
				    resp->ru.ru_stime.tv_sec % 60,
				    resp->ru.ru_stime.tv_sec / 10000);
			break;
		    case 'U':		/* User time.  */
			fprintf (fp, "%ld.%02ld",
				resp->ru.ru_utime.tv_sec,
				resp->ru.ru_utime.TV_MSEC / 10);
			break;
		    case 'u':		/* User time.  */
			if (resp->ru.ru_utime.tv_sec >= 3600)	/* One hour -> h:m:s.  */
			    fprintf (fp, "%ldh %ldm %02lds",
				    resp->ru.ru_utime.tv_sec / 3600,
				    (resp->ru.ru_utime.tv_sec % 3600) / 60,
				    resp->ru.ru_utime.tv_sec % 60);
			else
			    fprintf (fp, "%ldm %ld.%02lds",	/* -> m:s.  */
				    resp->ru.ru_utime.tv_sec / 60,
				    resp->ru.ru_utime.tv_sec % 60,
				    resp->ru.ru_utime.tv_sec / 10000);
			break;
		    case 'W':		/* Times swapped out.  */
			fprintf (fp, "%ld", resp->ru.ru_nswap);
			break;
		    case 'X':		/* Average shared text size.  */
			fprintf (fp, "%lu",
				MSEC_TO_TICKS (v) == 0 ? 0 :
				ptok ((UL) resp->ru.ru_ixrss) / MSEC_TO_TICKS (v));
			break;
		    case 'Z':		/* Page size.  */
			fprintf (fp, "%d", getpagesize ());
			break;
		    case 'c':		/* Involuntary context switches.  */
			fprintf (fp, "%ld", resp->ru.ru_nivcsw);
			break;
		    case 'e':		/* Elapsed real time in seconds.  */
			fprintf (fp, "%ld.%02ld",
				resp->elapsed.tv_sec,
				resp->elapsed.tv_usec / 10000);
			break;
		    case 'k':		/* Signals delivered.  */
			fprintf (fp, "%ld", resp->ru.ru_nsignals);
			break;
		    case 'p':		/* Average stack segment.  */
			fprintf (fp, "%lu",
				MSEC_TO_TICKS (v) == 0 ? 0 :
				ptok ((UL) resp->ru.ru_isrss) / MSEC_TO_TICKS (v));
			break;
		    case 'r':		/* Incoming socket messages received.  */
			fprintf (fp, "%ld", resp->ru.ru_msgrcv);
			break;
		    case 's':		/* Outgoing socket messages sent.  */
			fprintf (fp, "%ld", resp->ru.ru_msgsnd);
			break;
		    case 't':		/* Average resident set size.  */
			fprintf (fp, "%lu",
				MSEC_TO_TICKS (v) == 0 ? 0 :
				ptok ((UL) resp->ru.ru_idrss) / MSEC_TO_TICKS (v));
			break;
		    case 'w':		/* Voluntary context switches.  */
			fprintf (fp, "%ld", resp->ru.ru_nvcsw);
			break;
		    case 'x':		/* Exit status.  */
			fprintf (fp, "%d", WEXITSTATUS (resp->waitstatus));
			break;
		    case '\0':
			putc ('?', fp);
			return;
		    default:
			putc ('?', fp);
			putc (*fmt, fp);
		}
		++fmt;
		break;

	    case '\\':		/* Format escape.  */
		switch (*++fmt)
		{
		    case 't':
			putc ('\t', fp);
			break;
		    case 'n':
			putc ('\n', fp);
			break;
		    case '\\':
			putc ('\\', fp);
			break;
		    default:
			putc ('?', fp);
			putc ('\\', fp);
			putc (*fmt, fp);
		}
		++fmt;
		break;

	    default:
		putc (*fmt++, fp);
	}

	if (ferror (fp))
	    error_msg_and_die("write error");
    }
    putc ('\n', fp);

    if (ferror (fp))
	error_msg_and_die("write error");
}
Example #17
0
static int
read_from_pipe(const char *cmd, void **p_buf, size_t *p_read_sz)
{
	int err = 0;
	void *buf = NULL;
	FILE *file = NULL;
	size_t read_sz = 0, buf_sz = 0;
	char serr[STRERR_BUFSIZE];

	file = popen(cmd, "r");
	if (!file) {
		pr_err("ERROR: unable to popen cmd: %s\n",
		       str_error_r(errno, serr, sizeof(serr)));
		return -EINVAL;
	}

	while (!feof(file) && !ferror(file)) {
		/*
		 * Make buf_sz always have obe byte extra space so we
		 * can put '\0' there.
		 */
		if (buf_sz - read_sz < READ_SIZE + 1) {
			void *new_buf;

			buf_sz = read_sz + READ_SIZE + 1;
			new_buf = realloc(buf, buf_sz);

			if (!new_buf) {
				pr_err("ERROR: failed to realloc memory\n");
				err = -ENOMEM;
				goto errout;
			}

			buf = new_buf;
		}
		read_sz += fread(buf + read_sz, 1, READ_SIZE, file);
	}

	if (buf_sz - read_sz < 1) {
		pr_err("ERROR: internal error\n");
		err = -EINVAL;
		goto errout;
	}

	if (ferror(file)) {
		pr_err("ERROR: error occurred when reading from pipe: %s\n",
		       str_error_r(errno, serr, sizeof(serr)));
		err = -EIO;
		goto errout;
	}

	err = WEXITSTATUS(pclose(file));
	file = NULL;
	if (err) {
		err = -EINVAL;
		goto errout;
	}

	/*
	 * If buf is string, give it terminal '\0' to make our life
	 * easier. If buf is not string, that '\0' is out of space
	 * indicated by read_sz so caller won't even notice it.
	 */
	((char *)buf)[read_sz] = '\0';

	if (!p_buf)
		free(buf);
	else
		*p_buf = buf;

	if (p_read_sz)
		*p_read_sz = read_sz;
	return 0;

errout:
	if (file)
		pclose(file);
	free(buf);
	if (p_buf)
		*p_buf = NULL;
	if (p_read_sz)
		*p_read_sz = 0;
	return err;
}
Example #18
0
static char *feh_magick_load_image(char *filename)
{
	char argv_fd[12];
	char *basename;
	char *tmpname;
	char *sfn;
	int fd = -1, devnull = -1;
	int status;

	if (opt.magick_timeout < 0)
		return NULL;

	basename = strrchr(filename, '/');

	if (basename == NULL)
		basename = filename;
	else
		basename++;

	tmpname = feh_unique_filename("/tmp/", basename);

	if (strlen(tmpname) > (NAME_MAX-6))
		tmpname[NAME_MAX-7] = '\0';

	sfn = estrjoin("_", tmpname, "XXXXXX", NULL);
	free(tmpname);

	fd = mkstemp(sfn);

	if (fd == -1)
		return NULL;

	snprintf(argv_fd, sizeof(argv_fd), "png:fd:%d", fd);

	if ((childpid = fork()) == 0) {

		/* discard convert output */
		devnull = open("/dev/null", O_WRONLY);
		dup2(devnull, 0);
		dup2(devnull, 1);
		dup2(devnull, 2);

		/*
		 * convert only accepts SIGINT via killpg, a normal kill doesn't work
		 */
		setpgid(0, 0);

		execlp("convert", "convert", filename, argv_fd, NULL);
		exit(1);
	}
	else {
		alarm(opt.magick_timeout);
		waitpid(childpid, &status, 0);
		alarm(0);
		if (!WIFEXITED(status) || (WEXITSTATUS(status) != 0)) {
			close(fd);
			unlink(sfn);
			free(sfn);
			sfn = NULL;

			if (!opt.quiet) {
				if (WIFSIGNALED(status))
					weprintf("%s - Conversion took too long, skipping",
						filename);
			}

			/*
			 * Reap child.  The previous waitpid call was interrupted by
			 * alarm, but convert doesn't terminate immediately.
			 * XXX
			 * normally, if (WIFSIGNALED(status)) waitpid(childpid, &status, 0);
			 * would suffice. However, as soon as feh has its own window,
			 * this doesn't work anymore and the following workaround is
			 * required. Hm.
			 */
			waitpid(-1, &status, 0);
		}
		childpid = 0;
	}

	return sfn;
}
Example #19
0
/*
  handle stdout/stderr from the child
 */
static void samba_runcmd_io_handler(struct tevent_context *ev,
				    struct tevent_fd *fde,
				    uint16_t flags,
				    void *private_data)
{
	struct tevent_req *req = talloc_get_type_abort(private_data,
				 struct tevent_req);
	struct samba_runcmd_state *state = tevent_req_data(req,
					   struct samba_runcmd_state);
	int level;
	char *p;
	int n, fd;

	if (fde == state->fde_stdout) {
		level = state->stdout_log_level;
		fd = state->fd_stdout;
	} else if (fde == state->fde_stderr) {
		level = state->stderr_log_level;
		fd = state->fd_stderr;
	} else {
		return;
	}

	if (!(flags & TEVENT_FD_READ)) {
		return;
	}

	n = read(fd, &state->buf[state->buf_used],
		 sizeof(state->buf) - state->buf_used);
	if (n > 0) {
		state->buf_used += n;
	} else if (n == 0) {
		if (fde == state->fde_stdout) {
			talloc_free(fde);
			state->fde_stdout = NULL;
		}
		if (fde == state->fde_stderr) {
			talloc_free(fde);
			state->fde_stderr = NULL;
		}
		if (state->fde_stdout == NULL &&
		    state->fde_stderr == NULL) {
			int status;
			/* the child has closed both stdout and
			 * stderr, assume its dead */
			pid_t pid = waitpid(state->pid, &status, 0);
			if (pid != state->pid) {
				if (errno == ECHILD) {
					/* this happens when the
					   parent has set SIGCHLD to
					   SIG_IGN. In that case we
					   can only get error
					   information for the child
					   via its logging. We should
					   stop using SIG_IGN on
					   SIGCHLD in the standard
					   process model.
					*/
					DEBUG(0, ("Error in waitpid() unexpectedly got ECHILD "
						  "for %s child %d - %s, "
						  "someone has set SIGCHLD to SIG_IGN!\n",
					state->arg0, (int)state->pid, strerror(errno)));
					tevent_req_error(req, errno);
					return;
				}
				DEBUG(0,("Error in waitpid() for child %s - %s \n",
					 state->arg0, strerror(errno)));
				if (errno == 0) {
					errno = ECHILD;
				}
				tevent_req_error(req, errno);
				return;
			}
			status = WEXITSTATUS(status);
			DEBUG(3,("Child %s exited with status %d - %s\n",
				 state->arg0, status, strerror(status)));
			if (status != 0) {
				tevent_req_error(req, status);
				return;
			}

			tevent_req_done(req);
			return;
		}
		return;
	}

	while (state->buf_used > 0 &&
	       (p = (char *)memchr(state->buf, '\n', state->buf_used)) != NULL) {
		int n1 = (p - state->buf)+1;
		int n2 = n1 - 1;
		/* swallow \r from child processes */
		if (n2 > 0 && state->buf[n2-1] == '\r') {
			n2--;
		}
		DEBUG(level,("%s: %*.*s\n", state->arg0, n2, n2, state->buf));
		memmove(state->buf, p+1, sizeof(state->buf) - n1);
		state->buf_used -= n1;
	}

	/* the buffer could have completely filled - unfortunately we have
	   no choice but to dump it out straight away */
	if (state->buf_used == sizeof(state->buf)) {
		DEBUG(level,("%s: %*.*s\n",
			     state->arg0, state->buf_used,
			     state->buf_used, state->buf));
		state->buf_used = 0;
	}
}
Example #20
0
extern int slurm_jobcomp_log_record(struct job_record *job_ptr)
{
	char usr_str[32], grp_str[32], start_str[32], end_str[32], time_str[32];
	char *json_str = NULL, *script_str = NULL, *state_string = NULL;
	char *exit_code_str = NULL, *derived_ec_str = NULL, *script = NULL;
	enum job_states job_state;
	int i, tmp_int, tmp_int2;
	time_t elapsed_time;
	uint32_t time_limit;
	uint16_t ntasks_per_node;
	struct job_node *jnode;

	if (list_count(jobslist) > MAX_JOBS) {
		error("%s: Limit of %d enqueued jobs in memory waiting to be indexed reached. Job %lu discarded",
		      plugin_type, MAX_JOBS, (unsigned long)job_ptr->job_id);
		return SLURM_ERROR;
	}

	_get_user_name(job_ptr->user_id, usr_str, sizeof(usr_str));
	_get_group_name(job_ptr->group_id, grp_str, sizeof(grp_str));

	if ((job_ptr->time_limit == NO_VAL) && job_ptr->part_ptr)
		time_limit = job_ptr->part_ptr->max_time;
	else
		time_limit = job_ptr->time_limit;

	if (job_ptr->job_state & JOB_RESIZING) {
		time_t now = time(NULL);
		state_string = job_state_string(job_ptr->job_state);
		if (job_ptr->resize_time) {
			_make_time_str(&job_ptr->resize_time, start_str,
				       sizeof(start_str));
		} else {
			_make_time_str(&job_ptr->start_time, start_str,
				       sizeof(start_str));
		}
		_make_time_str(&now, end_str, sizeof(end_str));
	} else {
		/* Job state will typically have JOB_COMPLETING or JOB_RESIZING
		 * flag set when called. We remove the flags to get the eventual
		 * completion state: JOB_FAILED, JOB_TIMEOUT, etc. */
		job_state = job_ptr->job_state & JOB_STATE_BASE;
		state_string = job_state_string(job_state);
		if (job_ptr->resize_time) {
			_make_time_str(&job_ptr->resize_time, start_str,
				       sizeof(start_str));
		} else if (job_ptr->start_time > job_ptr->end_time) {
			/* Job cancelled while pending and
			 * expected start time is in the future. */
			snprintf(start_str, sizeof(start_str), "Unknown");
		} else {
			_make_time_str(&job_ptr->start_time, start_str,
				       sizeof(start_str));
		}
		_make_time_str(&job_ptr->end_time, end_str, sizeof(end_str));
	}

	elapsed_time = job_ptr->end_time - job_ptr->start_time;

	tmp_int = tmp_int2 = 0;
	if (job_ptr->derived_ec == NO_VAL)
		;
	else if (WIFSIGNALED(job_ptr->derived_ec))
		tmp_int2 = WTERMSIG(job_ptr->derived_ec);
	else if (WIFEXITED(job_ptr->derived_ec))
		tmp_int = WEXITSTATUS(job_ptr->derived_ec);
	xstrfmtcat(derived_ec_str, "%d:%d", tmp_int, tmp_int2);

	tmp_int = tmp_int2 = 0;
	if (job_ptr->exit_code == NO_VAL)
		;
	else if (WIFSIGNALED(job_ptr->exit_code))
		tmp_int2 = WTERMSIG(job_ptr->exit_code);
	else if (WIFEXITED(job_ptr->exit_code))
		tmp_int = WEXITSTATUS(job_ptr->exit_code);
	xstrfmtcat(exit_code_str, "%d:%d", tmp_int, tmp_int2);

	json_str = xstrdup_printf(JOBCOMP_DATA_FORMAT,
				job_ptr->job_id, usr_str,
				job_ptr->user_id, grp_str,
				job_ptr->group_id, start_str,
				end_str, elapsed_time,
				job_ptr->partition, job_ptr->alloc_node,
				job_ptr->nodes, job_ptr->total_cpus,
				job_ptr->total_nodes,
				derived_ec_str,
				exit_code_str, state_string,
				((float) elapsed_time *
				 (float) job_ptr->total_cpus) /
				 (float) 3600);

	if (job_ptr->array_task_id != NO_VAL) {
		xstrfmtcat(json_str, ",\"array_job_id\":%lu",
			   (unsigned long) job_ptr->array_job_id);
		xstrfmtcat(json_str, ",\"array_task_id\":%lu",
			   (unsigned long) job_ptr->array_task_id);
	}

	if (job_ptr->pack_job_id != NO_VAL) {
		xstrfmtcat(json_str, ",\"pack_job_id\":%lu",
			   (unsigned long) job_ptr->pack_job_id);
		xstrfmtcat(json_str, ",\"pack_job_offset\":%lu",
			   (unsigned long) job_ptr->pack_job_offset);
	}

	if (job_ptr->details && job_ptr->details->submit_time) {
		_make_time_str(&job_ptr->details->submit_time,
			       time_str, sizeof(time_str));
		xstrfmtcat(json_str, ",\"@submit\":\"%s\"", time_str);
	}

	if (job_ptr->details && job_ptr->details->begin_time) {
		_make_time_str(&job_ptr->details->begin_time,
			       time_str, sizeof(time_str));
		xstrfmtcat(json_str, ",\"@eligible\":\"%s\"", time_str);
		if (job_ptr->start_time) {
			int64_t queue_wait = (int64_t)difftime(
				job_ptr->start_time,
				job_ptr->details->begin_time);
			xstrfmtcat(json_str, ",\"queue_wait\":%"PRIi64,
				   queue_wait);
		}
	}

	if (job_ptr->details
	    && (job_ptr->details->work_dir && job_ptr->details->work_dir[0])) {
		xstrfmtcat(json_str, ",\"work_dir\":\"%s\"",
			   job_ptr->details->work_dir);
	}

	if (job_ptr->details
	    && (job_ptr->details->std_err && job_ptr->details->std_err[0])) {
		xstrfmtcat(json_str, ",\"std_err\":\"%s\"",
			   job_ptr->details->std_err);
	}

	if (job_ptr->details
	    && (job_ptr->details->std_in && job_ptr->details->std_in[0])) {
		xstrfmtcat(json_str, ",\"std_in\":\"%s\"",
			   job_ptr->details->std_in);
	}

	if (job_ptr->details
	    && (job_ptr->details->std_out && job_ptr->details->std_out[0])) {
		xstrfmtcat(json_str, ",\"std_out\":\"%s\"",
			   job_ptr->details->std_out);
	}

	if (job_ptr->assoc_ptr != NULL) {
		xstrfmtcat(json_str, ",\"cluster\":\"%s\"",
			   job_ptr->assoc_ptr->cluster);
	}

	if (job_ptr->qos_ptr != NULL) {
		xstrfmtcat(json_str, ",\"qos\":\"%s\"", job_ptr->qos_ptr->name);
	}

	if (job_ptr->details && (job_ptr->details->num_tasks != NO_VAL)) {
		xstrfmtcat(json_str, ",\"ntasks\":%u",
			   job_ptr->details->num_tasks);
	}

	if (job_ptr->details
	    && (job_ptr->details->ntasks_per_node != NO_VAL16)) {
		ntasks_per_node = job_ptr->details->ntasks_per_node;
		xstrfmtcat(json_str, ",\"ntasks_per_node\":%hu",
			   ntasks_per_node);
	}

	if (job_ptr->details
	    && (job_ptr->details->cpus_per_task != NO_VAL16)) {
		xstrfmtcat(json_str, ",\"cpus_per_task\":%hu",
			   job_ptr->details->cpus_per_task);
	}

	if (job_ptr->details
	    && (job_ptr->details->orig_dependency
		&& job_ptr->details->orig_dependency[0])) {
		xstrfmtcat(json_str, ",\"orig_dependency\":\"%s\"",
			   job_ptr->details->orig_dependency);
	}

	if (job_ptr->details
	    && (job_ptr->details->exc_nodes
		&& job_ptr->details->exc_nodes[0])) {
		xstrfmtcat(json_str, ",\"excluded_nodes\":\"%s\"",
			   job_ptr->details->exc_nodes);
	}

	if (time_limit != INFINITE) {
		xstrfmtcat(json_str, ",\"time_limit\":%lu",
			   (unsigned long) time_limit * 60);
	}

	if (job_ptr->name && job_ptr->name[0])
		xstrfmtcat(json_str, ",\"job_name\":\"%s\"", job_ptr->name);

	if (job_ptr->resv_name && job_ptr->resv_name[0]) {
		xstrfmtcat(json_str, ",\"reservation_name\":\"%s\"",
			   job_ptr->resv_name);
	}

	if (job_ptr->wckey && job_ptr->wckey[0])
		xstrfmtcat(json_str, ",\"wc_key\":\"%s\"", job_ptr->wckey);

	if (job_ptr->gres_req && job_ptr->gres_req[0]) {
		xstrfmtcat(json_str, ",\"gres_req\":\"%s\"", job_ptr->gres_req);
	}

	if (job_ptr->gres_alloc && job_ptr->gres_alloc[0]) {
		xstrfmtcat(json_str, ",\"gres_alloc\":\"%s\"",
			   job_ptr->gres_alloc);
	}

	if (job_ptr->account && job_ptr->account[0]) {
		xstrfmtcat(json_str, ",\"account\":\"%s\"", job_ptr->account);
	}

	script = get_job_script(job_ptr);
	if (script && script[0]) {
		script_str = _json_escape(script);
		xstrfmtcat(json_str, ",\"script\":\"%s\"", script_str);
		xfree(script_str);
	}
	xfree(script);

	if (job_ptr->assoc_ptr) {
		assoc_mgr_lock_t locks = { READ_LOCK, NO_LOCK, NO_LOCK, NO_LOCK,
					   NO_LOCK, NO_LOCK, NO_LOCK };
		slurmdb_assoc_rec_t *assoc_ptr = job_ptr->assoc_ptr;
		char *parent_accounts = NULL;
		char **acc_aux = NULL;
		int nparents = 0;

		assoc_mgr_lock(&locks);

		/* Start at the first parent and go up. When studying
		 * this code it was slightly faster to do 2 loops on
		 * the association linked list and only 1 xmalloc but
		 * we opted for cleaner looking code and going with a
		 * realloc. */
		while (assoc_ptr) {
			if (assoc_ptr->acct) {
				acc_aux = xrealloc(acc_aux,
						   sizeof(char *) *
						   (nparents + 1));
				acc_aux[nparents++] = assoc_ptr->acct;
			}
			assoc_ptr = assoc_ptr->usage->parent_assoc_ptr;
		}

		for (i = nparents - 1; i >= 0; i--)
			xstrfmtcat(parent_accounts, "/%s", acc_aux[i]);
		xfree(acc_aux);

		xstrfmtcat(json_str, ",\"parent_accounts\":\"%s\"",
			   parent_accounts);

		xfree(parent_accounts);

		assoc_mgr_unlock(&locks);
	}

	xfree(derived_ec_str);
	xfree(exit_code_str);
	xstrcat(json_str, "}");
	jnode = xmalloc(sizeof(struct job_node));
	jnode->serialized_job = json_str;
	list_enqueue(jobslist, jnode);
	json_str = NULL;

	return SLURM_SUCCESS;
}
Example #21
0
// run
void runProcess(char* file, char* words[100]) {
	int errsv;
	pid_t pid;
	int status;
	int returnVal;
	int fd;

	pid = fork();
	if(pid < 0) { // error in fork
		errsv = errno;
		printf("myshell: fork failed: %s\n", strerror(errsv));
	} else if(pid == 0) { // child process
		// also allow space between </> and file!
		if(words[1]) {
			if(words[1][0] == '<') {
				strcpy(words[1], &words[1][1]);
				fd = open(words[1], O_RDONLY);
				if(fd < 0) {
					errsv = errno;
					printf("myshell: cannot open input file %s: %s\n", words[1], strerror(errsv));
					exit(1);
				} else {
					dup2(fd, 0);
				}
			}/* else if(words[1][0] == '>') {
				strcpy(words[1], &words[1][1]);
				fd = creat(words[1], S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
				if(fd < 0) {
					errsv = errno;
					printf("myshell: cannot open output file %s: %s\n", words[1], strerror(errsv));
					exit(1);
				} else {
					dup2(fd, 1);
				}
			}*/
		}
		if(words[2]) {
			if(words[2][0] == '>') {
				strcpy(words[2], &words[2][1]);
				fd = creat(words[2], S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
				if(fd < 0) {
					errsv = errno;
					printf("myshell: cannot open output file %s: %s\n", words[2], strerror(errsv));
					exit(1);
				} else {
					dup2(fd, 1);
				}
			}
		}
		returnVal = execvp(file, words);
		if(returnVal < 0) { // error in execute
			errsv = errno;
			printf("myshell: cannot execute %s: %s\n", file, strerror(errsv));
			exit(1); // terminate child with status 1 if command cannot execute
		}
	} else { // parent process
		returnVal = waitpid(pid, &status, 0); // not sure about third argument
		if(returnVal < 0) { // error in wait
			errsv = errno;
			printf("myshell: wait failed: %s\n", strerror(errsv));
		} else {
			if(WIFEXITED(status)) { // child process exited normally (by returning or calling exit())
				printf("myshell: process %i exited normally with status %i\n", pid, WEXITSTATUS(status));
			} else if(WIFSIGNALED(status)) { // child process terminated with signal
				printf("myshell: process %i exited abnormally with signal %i: %s\n", pid, WTERMSIG(status), strsignal(WTERMSIG(status)));
			} // else?
		}
	}

}
Example #22
0
//------------------------------------------------------------------------------
// Name: exit_code() const
// Desc: if it was an exit event, what was the status
//------------------------------------------------------------------------------
int DebugEvent::exit_code() const {
	return WEXITSTATUS(status);
}
Example #23
0
int rpmDoDigest(int algo, const char * fn,int asAscii,
                unsigned char * digest, rpm_loff_t * fsizep)
{
    const char * path;
    urltype ut = urlPath(fn, &path);
    unsigned char * dig = NULL;
    size_t diglen, buflen = 32 * BUFSIZ;
    unsigned char *buf = xmalloc(buflen);
    FD_t fd;
    rpm_loff_t fsize = 0;
    pid_t pid = 0;
    int rc = 0;
    int fdno;

    fdno = open_dso(path, &pid, &fsize);
    if (fdno < 0) {
	rc = 1;
	goto exit;
    }

    switch(ut) {
    case URL_IS_PATH:
    case URL_IS_UNKNOWN:
    case URL_IS_HTTPS:
    case URL_IS_HTTP:
    case URL_IS_FTP:
    case URL_IS_HKP:
    case URL_IS_DASH:
    default:
	/* Either use the pipe to prelink -y or open the URL. */
	fd = (pid != 0) ? fdDup(fdno) : Fopen(fn, "r.ufdio");
	(void) close(fdno);
	if (fd == NULL || Ferror(fd)) {
	    rc = 1;
	    if (fd != NULL)
		(void) Fclose(fd);
	    break;
	}
	
	fdInitDigest(fd, algo, 0);
	fsize = 0;
	while ((rc = Fread(buf, sizeof(*buf), buflen, fd)) > 0)
	    fsize += rc;
	fdFiniDigest(fd, algo, (void **)&dig, &diglen, asAscii);
	if (dig == NULL || Ferror(fd))
	    rc = 1;

	(void) Fclose(fd);
	break;
    }

    /* Reap the prelink -y helper. */
    if (pid) {
	int status;
	(void) waitpid(pid, &status, 0);
	if (!WIFEXITED(status) || WEXITSTATUS(status))
	    rc = 1;
    }

exit:
    if (fsizep)
	*fsizep = fsize;
    if (!rc)
	memcpy(digest, dig, diglen);
    dig = _free(dig);
    free(buf);

    return rc;
}
Example #24
0
int main(int argc, char *argv[])
{
	int	fd;
	int	pid;
	pid_t	child;
	int	status;
	int	root_fd;

	exit_if(argc < 4,
		"Usage: %s pid imageid cmd [args...]", argv[0])

	pid = atoi(argv[1]);
	root_fd = openpidfd(pid, "root");

#define ns(_typ, _nam)							\
	fd = openpidfd(pid, _nam);					\
	pexit_if(setns(fd, _typ), "Unable to enter " _nam " namespace");

#if 0
	/* TODO(vc): Nspawn isn't employing CLONE_NEWUSER, disabled for now */
	ns(CLONE_NEWUSER, "ns/user");
#endif
	ns(CLONE_NEWIPC,  "ns/ipc");
	ns(CLONE_NEWUTS,  "ns/uts");
	ns(CLONE_NEWNET,  "ns/net");
	ns(CLONE_NEWPID,  "ns/pid");
	ns(CLONE_NEWNS,	  "ns/mnt");

	pexit_if(fchdir(root_fd) < 0,
		"Unable to chdir to pod root");
	pexit_if(chroot(".") < 0,
		"Unable to chroot");
	pexit_if(close(root_fd) == -1,
		"Unable to close root_fd");

	/* Fork is required to realize consequence of CLONE_NEWPID */
	pexit_if(((child = fork()) == -1),
		"Unable to fork");

/* some stuff make the argv->args copy less cryptic */
#define ENTER_ARGV_FWD_OFFSET		3
#define DIAGEXEC_ARGV_FWD_OFFSET	6
#define args_fwd_idx(_idx) \
	((_idx - ENTER_ARGV_FWD_OFFSET) + DIAGEXEC_ARGV_FWD_OFFSET)

	if(child == 0) {
		char		root[PATH_MAX];
		char		env[PATH_MAX];
		char		*args[args_fwd_idx(argc) + 1 /* NULL terminator */];
		int		i;

		/* Child goes on to execute /diagexec */

		exit_if(snprintf(root, sizeof(root),
				 "/opt/stage2/%s/rootfs", argv[2]) == sizeof(root),
			"Root path overflow");

		exit_if(snprintf(env, sizeof(env),
				 "/rkt/env/%s", argv[2]) == sizeof(env),
			"Env path overflow");

		args[0] = "/diagexec";
		args[1] = root;
		args[2] = "/";	/* TODO(vc): plumb this into app.WorkingDirectory */
		args[3] = env;
		args[4] = "0"; /* uid */
		args[5] = "0"; /* gid */
		for(i = ENTER_ARGV_FWD_OFFSET; i < argc; i++) {
			args[args_fwd_idx(i)] = argv[i];
		}
		args[args_fwd_idx(i)] = NULL;

		pexit_if(execv(args[0], args) == -1,
			"Exec failed");
	}

	/* Wait for child, nsenter-like */
	for(;;) {
		if(waitpid(child, &status, WUNTRACED) == pid &&
		   (WIFSTOPPED(status))) {
			kill(getpid(), SIGSTOP);
			/* the above stops us, upon receiving SIGCONT we'll
			 * continue here and inform our child */
			kill(child, SIGCONT);
		} else {
			break;
		}
	}

	if(WIFEXITED(status)) {
		exit(WEXITSTATUS(status));
	} else if(WIFSIGNALED(status)) {
		kill(getpid(), WTERMSIG(status));
	}

	return EXIT_FAILURE;
}
Example #25
0
File: 2-1.c Project: Nan619/ltp-ddt
/* Main entry point. */
int main(int argc, char *argv[])
{
	int ret;
	int sc;
	pthread_mutexattr_t ma;

	testdata_t *td;
	testdata_t alternativ;

	int do_fork;

	pid_t child_pr = 0, chkpid;
	int status;
	pthread_t child_th;

	long pshared, mf;

	/* Initialize output */
	output_init();

	/* Test system abilities */
	pshared = sysconf(_SC_THREAD_PROCESS_SHARED);
	mf = sysconf(_SC_MAPPED_FILES);

#if VERBOSE > 0
	output("Test starting\n");
	output("System abilities:\n");
	output(" TSH : %li\n", pshared);
	output(" MF  : %li\n", mf);
	if ((mf < 0) || (pshared < 0))
		output("Process-shared attributes won't be tested\n");
#endif

/**********
 * Allocate space for the testdata structure
 */
	if (mf < 0) {
		/* Cannot mmap a file (or not interested in this), we use an alternative method */
		td = &alternativ;
		pshared = -1;	/* We won't do this testing anyway */
#if VERBOSE > 0
		output("Testdata allocated in the process memory.\n");
#endif
	} else {
		/* We will place the test data in a mmaped file */
		char filename[] = "/tmp/mutex_trylock_2-1-XXXXXX";
		size_t sz;
		void *mmaped;
		int fd;
		char *tmp;

		/* We now create the temp files */
		fd = mkstemp(filename);
		if (fd == -1) {
			UNRESOLVED(errno,
				   "Temporary file could not be created");
		}

		/* and make sure the file will be deleted when closed */
		unlink(filename);

#if VERBOSE > 1
		output("Temp file created (%s).\n", filename);
#endif

		sz = (size_t) sysconf(_SC_PAGESIZE);

		tmp = calloc(1, sz);
		if (tmp == NULL) {
			UNRESOLVED(errno, "Memory allocation failed");
		}

		/* Write the data to the file.  */
		if (write(fd, tmp, sz) != (ssize_t) sz) {
			UNRESOLVED(sz, "Writting to the file failed");
		}

		free(tmp);

		/* Now we can map the file in memory */
		mmaped =
		    mmap(NULL, sz, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
		if (mmaped == MAP_FAILED) {
			UNRESOLVED(errno, "mmap failed");
		}

		td = (testdata_t *) mmaped;

		/* Our datatest structure is now in shared memory */
#if VERBOSE > 1
		output("Testdata allocated in shared memory.\n");
#endif
	}

/**********
 * For each test scenario, initialize the attributes and other variables.
 * Do the whole thing for each time to test.
 */
	for (sc = 0; sc < NSCENAR; sc++) {
#if VERBOSE > 1
		output("[parent] Preparing attributes for: %s\n",
		       scenarii[sc].descr);
#endif
		/* set / reset everything */
		do_fork = 0;
		ret = pthread_mutexattr_init(&ma);
		if (ret != 0) {
			UNRESOLVED(ret,
				   "[parent] Unable to initialize the mutex attribute object");
		}

		/* Set the mutex type */
		ret = pthread_mutexattr_settype(&ma, scenarii[sc].m_type);
		if (ret != 0) {
			UNRESOLVED(ret, "[parent] Unable to set mutex type");
		}
#if VERBOSE > 1
		output("[parent] Mutex type : %i\n", scenarii[sc].m_type);
#endif

		/* Set the pshared attributes, if supported */
		if ((pshared > 0) && (scenarii[sc].m_pshared != 0)) {
			ret =
			    pthread_mutexattr_setpshared(&ma,
							 PTHREAD_PROCESS_SHARED);
			if (ret != 0) {
				UNRESOLVED(ret,
					   "[parent] Unable to set the mutex process-shared");
			}
#if VERBOSE > 1
			output("[parent] Mutex is process-shared\n");
#endif
		}
#if VERBOSE > 1
		else {
			output("[parent] Mutex is process-private\n");
		}
#endif

		/* Tell whether the test will be across processes */
		if ((pshared > 0) && (scenarii[sc].fork != 0)) {
			do_fork = 1;
#if VERBOSE > 1
			output("[parent] Child will be a new process\n");
#endif
		}
#if VERBOSE > 1
		else {
			output("[parent] Child will be a new thread\n");
		}
#endif

/**********
 * Initialize the testdata_t structure with the previously defined attributes
 */
		/* Initialize the mutex */
		ret = pthread_mutex_init(&(td->mtx), &ma);
		if (ret != 0) {
			UNRESOLVED(ret, "[parent] Mutex init failed");
		}

		/* Initialize the other datas from the test structure */
		td->status = 0;

/**********
 * Proceed to the actual testing
 */
		/* Trylock the mutex twice before creating children */
		ret = pthread_mutex_trylock(&(td->mtx));
		if (ret != 0) {
			UNRESOLVED(ret, "[parent] Unable to trylock the mutex");
		}
		ret = pthread_mutex_trylock(&(td->mtx));

		if (scenarii[sc].m_type == PTHREAD_MUTEX_RECURSIVE) {
			if (ret != 0) {
				FAILED
				    ("Failed to pthread_mutex_trylock() twice a recursive mutex");
			}

			/* Unlock once so the count is "1" */
			ret = pthread_mutex_unlock(&(td->mtx));
			if (ret != 0) {
				UNRESOLVED(ret, "Failed to unlock the mutex");
			}
		} else if (ret == 0) {
			UNRESOLVED(-1,
				   "Main was able to pthread_mutex_trylock() twice without error");
		}

		/* Create the children */
		if (do_fork != 0) {
			/* We are testing across processes */
			child_pr = fork();
			if (child_pr == -1) {
				UNRESOLVED(errno, "[parent] Fork failed");
			}

			if (child_pr == 0) {
#if VERBOSE > 3
				output
				    ("[child] Child process is starting...\n");
#endif

				if (tf((void *)td) != NULL) {
					UNRESOLVED(-1,
						   "[child] Got an unexpected return value from test function");
				} else {
					/* We cannot use the PASSED macro here since it would terminate the output */
					exit(0);
				}
			}
			/* Only the parent process goes further */
		} else {	/* do_fork == 0 */

			/* We are testing across two threads */
			ret = pthread_create(&child_th, NULL, tf, td);
			if (ret != 0) {
				UNRESOLVED(ret,
					   "[parent] Unable to create the child thread.");
			}
		}

		/* Wait for the child to terminate */
		if (do_fork != 0) {
			/* We were testing across processes */
			ret = 0;
			chkpid = waitpid(child_pr, &status, 0);
			if (chkpid != child_pr) {
				output("Expected pid: %i. Got %i\n",
				       (int)child_pr, (int)chkpid);
				UNRESOLVED(errno, "Waitpid failed");
			}
			if (WIFSIGNALED(status)) {
				output("Child process killed with signal %d\n",
				       WTERMSIG(status));
				UNRESOLVED(-1, "Child process was killed");
			}

			if (WIFEXITED(status)) {
				ret = WEXITSTATUS(status);
			} else {
				UNRESOLVED(-1,
					   "Child process was neither killed nor exited");
			}

			if (ret != 0) {
				exit(ret);	/* Output has already been closed in child */
			}

		} else {	/* child was a thread */

			ret = pthread_join(child_th, NULL);
			if (ret != 0) {
				UNRESOLVED(ret,
					   "[parent] Unable to join the thread");
			}
		}

		/* Check the child status */
		if (td->status != EBUSY) {
			output("Unexpected return value: %d (%s)\n", td->status,
			       strerror(td->status));
			FAILED
			    ("pthread_mutex_trylock() did not return EBUSY in the child");
		}

		/* Unlock the mutex */
		ret = pthread_mutex_unlock(&(td->mtx));
		if (ret != 0) {
			FAILED
			    ("Failed to unlock the mutex -- count is broken?");
		}

		ret = pthread_mutex_unlock(&(td->mtx));
		if (ret == 0) {
			FAILED
			    ("Was able to unlock once more the mutex -- count is broken?");
		}

/**********
 * Destroy the data
 */
		ret = pthread_mutex_destroy(&(td->mtx));
		if (ret != 0) {
			UNRESOLVED(ret, "Failed to destroy the mutex");
		}

		ret = pthread_mutexattr_destroy(&ma);
		if (ret != 0) {
			UNRESOLVED(ret,
				   "Failed to destroy the mutex attribute object");
		}

	}			/* Proceed to the next scenario */

#if VERBOSE > 0
	output("Test passed\n");
#endif

	PASSED;
}
Example #26
0
int main(int argc, char *argv[])
{
	struct timespec tssleep, tsbefore, tsafter, tsremain;
	int pid;
	struct sigaction act;

	if (clock_gettime(CLOCK_REALTIME, &tsbefore) != 0) {
		perror("clock_gettime() did not return success\n");
		return PTS_UNRESOLVED;
	}

	if ((pid = fork()) == 0) {
		/* child here */
		int sleptplusremaining;

		act.sa_handler=handler;
		act.sa_flags=0;
		if (sigemptyset(&act.sa_mask) != 0) {
			perror("sigemptyset() did not return success\n");
			return CHILDFAIL;
		}
		if (sigaction(SIGABRT, &act, 0) != 0) {
			perror("sigaction() did not return success\n");
			return CHILDFAIL;
		}
		tssleep.tv_sec=SLEEPSEC;
		tssleep.tv_nsec=0;
		if (clock_nanosleep(CLOCK_REALTIME, 0,
					&tssleep, &tsremain) == EINTR) {
			if (clock_gettime(CLOCK_REALTIME, &tsafter) != 0) {
				perror("clock_gettime() failed\n");
				return CHILDFAIL;
			}
			sleptplusremaining = (tsafter.tv_sec-tsbefore.tv_sec) +
							tsremain.tv_sec;

			if (abs(sleptplusremaining - SLEEPSEC) <= OKDELTA) {
				printf("PASS - within %d difference\n",
					abs(sleptplusremaining - SLEEPSEC));
					return CHILDPASS;
			} else {
				printf("FAIL - within %d difference\n",
					abs(sleptplusremaining - SLEEPSEC));
					return CHILDFAIL;
			}

			return CHILDFAIL;
		} else {
			printf("clock_nanosleep() did not return EINTR\n");
			return CHILDFAIL;
		}
	} else {
		/* parent here */
		int i;

		sleep(1);

		if (kill(pid, SIGABRT) != 0) {
			printf("Could not raise signal being tested\n");
			return PTS_UNRESOLVED;
		}

		if (wait(&i) == -1) {
			perror("Error waiting for child to exit\n");
			return PTS_UNRESOLVED;
		}

		if (WIFEXITED(i) && WEXITSTATUS(i)) {
			printf("Child exited normally\n");
			printf("Test PASSED\n");
			return PTS_PASS;
		} else {
			printf("Child did not exit normally.\n");
			printf("Test FAILED\n");
			return PTS_FAIL;
		}
	}

	return PTS_UNRESOLVED;
}
Example #27
0
static void
on_password_answer (password_answer_state_t   *answer_state,
                    const char                *answer,
                    ply_boot_client_t         *client)
{
  int exit_status;

  exit_status = 127;
  if (answer != NULL && answer[0] != KEY_CTRL_C)  /* a CTRL-C answer means the user canceled */
    {
      if (answer_state->command != NULL)
        {
          bool command_started = false;

          command_started = answer_via_command (answer_state->command, answer,
                                                &exit_status);

          if (command_started && (!WIFEXITED (exit_status) ||
              WEXITSTATUS (exit_status) != 0))
            {
              answer_state->number_of_tries_left--;

              if (answer_state->number_of_tries_left > 0)
                {
                  ply_boot_client_ask_daemon_for_password (answer_state->state->client,
                                                           answer_state->prompt,
                                                           (ply_boot_client_answer_handler_t)
                                                           on_password_answer,
                                                           (ply_boot_client_response_handler_t)
                                                           on_password_answer_failure,
                                                           answer_state);
                  return;
                }
            }
        }
      else
        {
          write (STDOUT_FILENO, answer, strlen (answer));
          exit_status = 0;
        }
    }
  else if (answer == NULL)
    {
      on_password_answer_failure (answer_state, answer_state->state->client);
    }

  if (WIFSIGNALED (exit_status))
    raise (WTERMSIG (exit_status));
  
  if (answer_state->pause)
    {
      ply_boot_client_tell_daemon_to_progress_unpause (client,
                                                       (ply_boot_client_response_handler_t)
                                                       (WEXITSTATUS (exit_status) ? on_failure : on_success),
                                                       (ply_boot_client_response_handler_t)
                                                       on_failure,
                                                       answer_state->state);
    }
  else
    ply_event_loop_exit (answer_state->state->loop, WEXITSTATUS (exit_status));
}
Example #28
0
int sys_cmd_initd(sysh_ctx_t syshc, char *value, uint16_t *out_rc, char **out_str){
    int sys_rc = MOD_OK;
    int rc = 0;
    pid_t pid;
    char *dpath, *daemon, *command, *p;
    static char *valid_commands[] = {"restart", "stop", "start", "reload", "enable", "disable", NULL};
    size_t len;
    bool valid = false;
    int i;
    
    dpath = daemon = command = p = NULL;

    if ( !value || !(p = strchr(value, ' '))  ){
        sys_rc = EINVAL;
        if ( asprintf(out_str, "Invalid argument list.") == -1 ){
            err("asprintf: %s\n", strerror(errno));
            *out_str = NULL;
        }
        goto done;
    }

    *p = '\0';
    daemon = strdup(value);
    *p = ' ';
    if ( asprintf(&dpath, "%s/%s", syshc->initd_dir, basename(daemon)) < 0 ){
        sys_rc = ENOMEM;
        goto done;
    }
    if ( access(dpath, X_OK) != 0 ){
        sys_rc = EPERM;
        if ( asprintf(out_str, "access:  %s", strerror(errno)) == -1 ){
            err("asprintf: %s\n", strerror(errno));
            *out_str = NULL;
        }
        goto done;
    }


    command = strdup(p+1);
    for (i=0; valid_commands[i]; i++){
        len = strlen(valid_commands[i]);
        if ( strnlen(command, len+1) != len )
            continue;
        if ( !strncmp(command, valid_commands[i], len) ){
            valid = true;
            break;
        }
    }

    if ( !valid ){
        sys_rc = EINVAL;
        if ( asprintf(out_str, "Invalid init command.") == -1 ){
            err("asprintf: %s\n", strerror(errno));
            *out_str = NULL;
        }
        goto done;
    }

    pid = fork();
    if ( pid == -1 ){
        sys_rc = errno;
        if ( asprintf(out_str, "fork:  %s", strerror(errno)) == -1 ){
            err("asprintf: %s\n", strerror(errno));
            *out_str = NULL;
        }
        goto done;
    }

    
    if ( pid == 0 ){
        char *argv[] = { dpath, command, NULL };
        char *envir[] = { NULL };
        rc = execve(dpath, argv, envir);
        exit(EXIT_FAILURE);
    } else {
        int status;
        /* Wait for the child to exit and grab the rc. */
        if ( waitpid( pid, &status, 0) != pid ){
            sys_rc = errno;
            if ( asprintf(out_str, "waitpid:  %s", strerror(errno)) ){
                err("asprintf: %s\n", strerror(errno));
                *out_str = NULL;
            }
            goto done;
        }
        if ( !(WIFEXITED(status) && WEXITSTATUS(status) == EXIT_SUCCESS) ){
            sys_rc = ECANCELED;
            if ( asprintf(out_str, "%s exited with failure.\n", daemon) == -1 ){
                err("asprintf: %s\n", strerror(errno));
                *out_str = NULL;
            }
        }
    }

    if ( asprintf(out_str, "%s %s success.\n", daemon, command) == -1 ){
        err("asprintf: %s\n", strerror(errno));
        *out_str = NULL;
    }

done:
    if (daemon) free(daemon);
    if (dpath) free(dpath);
    if (command) free(command);
    (*out_rc) = (uint16_t)sys_rc;
    return rc;
}
int copy(char str[64],char name[32],int sym)
{
	char *wdest=(char *)malloc(sizeof(char)*64);//"/tmp/";
	strcpy(wdest,"/myfolder/");
	char qqdest[24]="/myfolder/";
	char wtype[8]=".sqlite";
	char *qtype=".";
	
	//printf("~~~~~000%s\n", wdest);
	strcat(wdest,name);
	//printf("~~~~~111%s\n", wdest);
	strcat(qqdest,name);
	strcat(wdest,wtype);
	//printf("~~~~~222%s\n", wdest);
	//strcat(qqdest,qtype);
	int pid;
	if ((pid = fork()) < 0) 
	{
    	printf("fork ifuse error\n");
    	return 0;
	}
	else if (pid == 0) 
	{                                
    	if(sym==0) //qq
    	{
    		execl("/bin/cp","cp", "-r",str,qqdest, (char *)0 );   //-r delete
    	}
    	else if(sym==1) //weixin 
    	{
    		//printf("%s\n", name);
    		//printf("%s\n", wdest);
    		execl("/bin/cp","cp", str,wdest, (char *)0 );
    	}
    	else
    	{
    		execl("/bin/cp","cp","-r", str,"/myfolder/", (char *)0 );
    	}
	}
	free(wdest);
	int status;
	pid_t ret;
	ret=wait(&status);
	if(ret <0){
        perror("wait error");
        return 0;
    }
    if (WIFEXITED(status))
    {
        printf("copy normal exit status=%d\n", WEXITSTATUS(status));
        if(WEXITSTATUS(status)==1)
        {
        	return 0;
        }
        else
        {
        	return 1;
        }
    }
    else
    {
    	printf("thread encounter error\n");
    	return 0;
    }
    
   
}
Example #30
0
int main(int ac, char **av)
{

	int lc;
	char *msg;
	int status;
	pid_t child_pid;

	if ((msg = parse_opts(ac, av, NULL, NULL)) != NULL)
		tst_brkm(TBROK, NULL, "OPTION PARSING ERROR - %s", msg);

	setup();

	for (lc = 0; TEST_LOOPING(lc); lc++) {

		Tst_count = 0;

		switch (child_pid = FORK_OR_VFORK()) {

		case -1:
			/* fork() failed */
			tst_resm(TFAIL, "fork() failed");
			continue;

		case 0:
			/* Child */

			/* Switch to nobody user */
			if ((ltpuser = getpwnam(nobody_uid)) == NULL) {
				tst_brkm(TBROK, NULL, "\"nobody\" user"
					 "not present");
			}
			if (seteuid(ltpuser->pw_uid) == -1) {
				tst_resm(TWARN, "seteuid failed to "
					 "to set the effective uid to %d",
					 ltpuser->pw_uid);
				exit(1);
			}

			/*
			 * Call sched_setparam(2) with pid = getppid()
			 */
			TEST(sched_setparam(getppid(), &param));

			if ((TEST_RETURN == -1) && (TEST_ERRNO == EPERM)) {
				TEST_ERROR_LOG(TEST_ERRNO);
				exit(0);
			}

			tst_resm(TWARN|TTERRNO, "Test failed, sched_setparam()"
				 " returned : %ld",
				 TEST_RETURN);
			TEST_ERROR_LOG(TEST_ERRNO);
			exit(1);

		default:
			/* Parent */
			if ((waitpid(child_pid, &status, 0)) < 0) {
				tst_resm(TFAIL, "wait() failed");
				continue;
			}
			if ((WIFEXITED(status)) && (WEXITSTATUS(status) == 0)) {
				tst_resm(TPASS, "Test passed, Got EPERM");
			} else {
				tst_resm(TFAIL, "Test Failed");
			}
		}
	}

	cleanup();
	tst_exit();
}