dumping ground for random patches and texts
 help / color / mirror / Atom feed
* vfork example in Perl with Inline::C
@ 2016-02-07 12:39 Eric Wong
  0 siblings, 0 replies; only message in thread
From: Eric Wong @ 2016-02-07 12:39 UTC (permalink / raw)
  To: spew

Gotta be careful and not modify anything in the process after
vfork is called.

#!/usr/bin/perl -w
use IO::Handle;
use Inline C => <<'C';
#include <sys/types.h>
#include <unistd.h>

static char **av_to_c(AV *av)
{
	I32 max = av_len(av) + 1;
	I32 i;
	char **ret = calloc(max, sizeof(char *));

	for (i = 0; i < max; i++) {
		SV **sv = av_fetch(av, i, 0);
		if (sv)
			ret[i] = SvPV_nolen(*sv);
	}

	return ret;
}

int my_spawn(SV *file, SV *cmdref, SV *envref)
{
	AV *cmd = SvRV(cmdref);
	AV *env = SvRV(envref);
	char **argv;
	char **envp;
	const char *filename = SvPV_nolen(file);
	pid_t pid = -1;
	argv = av_to_c(cmd);
	if (!argv) goto free_envp;
	envp = av_to_c(env);
	if (!envp) goto free_argv;

	pid = vfork();
	if (pid == 0) {
		execve(filename, argv, envp);
	}
free_envp:
	free(envp);
free_argv:
	free(argv);
	return (int)pid;
}
C

use strict;
STDOUT->autoflush(1);
my $pid = my_spawn('/bin/echo', ['echo', 'hello'], ['HELLO=world']);
waitpid($pid, 0);
print "$?\n";

^ permalink raw reply	[flat|nested] only message in thread

only message in thread, other threads:[~2016-02-07 12:39 UTC | newest]

Thread overview: (only message) (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2016-02-07 12:39 vfork example in Perl with Inline::C Eric Wong

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).