Plan 9 from Bell Labs’s /usr/web/sources/contrib/nemo/root/acme/msgs/src/tcmd.c

Copyright © 2021 Plan 9 Foundation.
Distributed under the MIT License.
Download the Plan 9 distribution.


#include <u.h>
#include <libc.h>
#include <bio.h>
#include <thread.h>
#include "dat.h"

typedef struct Arg Arg;

struct Arg {
	int p[2];
	char**argv;
};

enum {
	Nargs = 64
};

static void
cmdproc(void* x)
{
	Arg*	a = x;
	char**	argv;

	argv = a->argv;
	close(a->p[0]);
	dup(a->p[1], 1);
	close(a->p[1]);
	procexec(nil, argv[0], argv);
	threadexits(nil);
}

char*
tcmdoutput(char* cmd, long *noutp)
{
	long	tot, n;
	Arg	a;
	char*	argv[Nargs];
	int	argc;
	char*	s;
	char*	out;
	long	sz;

	*noutp = -1;
	s = estrdup(cmd);
	argc = tokenize(s, argv, nelem(argv)-1);
	if(argc < 0)
		error("tcmdoutput: no args");
	argv[argc] = nil;
	if (pipe(a.p) < 0)
		error("no pipes");
	a.argv = argv;
	procrfork(cmdproc, &a, 8*1024, RFFDG|RFENVG);
	close(a.p[1]);
	sz = 16*1024;
	out = emalloc(sz);
	for(tot = 0; sz - tot > 1 ; tot +=n){
		n = read(a.p[0], out+tot, sz - tot);
		if (n <= 0)
			break;
		if(tot + n == sz){
			sz += 16*1024;
			out = erealloc(out, sz);
		}
	}
	free(s);
	close(a.p[0]);
	out[tot] = 0;
	*noutp = tot;
	return out;
}

Bell Labs OSI certified Powered by Plan 9

(Return to Plan 9 Home Page)

Copyright © 2021 Plan 9 Foundation. All Rights Reserved.
Comments to webmaster@9p.io.