Skip to content

Commit

Permalink
Lab util: xargs
Browse files Browse the repository at this point in the history
  • Loading branch information
foyoodo committed Mar 7, 2021
1 parent 285299d commit a1ceb89
Show file tree
Hide file tree
Showing 2 changed files with 82 additions and 0 deletions.
1 change: 1 addition & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,7 @@ UPROGS=\
$U/_usertests\
$U/_grind\
$U/_wc\
$U/_xargs\
$U/_zombie\


Expand Down
81 changes: 81 additions & 0 deletions user/xargs.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
#include "kernel/param.h"
#include "kernel/types.h"
#include "user/user.h"

int
fmtpargs(char **pargs, char *buf, int n)
{
int t = 0;
char *h = buf + 1, *p = buf + 1;
for (int i = 1; i < n; ++i) {
if (buf[i] == '\\' || buf[i] == '\"') {
pargs[t] = malloc(p - h);
memcpy(pargs[t++], h, p++ - h);
h = ++p;
++i;
} else {
++p;
}
}
return t;
}

void
fmtsargs(char **sargs, int at, char *buf, int n)
{
char *h = buf, *p = buf;
for (int i = 0; i <= n; ++i) {
if ((buf[i] == ' ' && (p - h)) || buf[i] == '\n') {
sargs[at] = malloc(p - h);
memcpy(sargs[at++], h, p - h);
h = ++p;
} else if (buf[i] == ' ') {
h = ++p;
} else {
++p;
}
}
}

int
main(int argc, char *argv[])
{
char buf[512];
int n;

if ((n = read(0, buf, sizeof buf)) < 0) {
fprintf(2, "xargc: failed to read buf\n");
exit(1);
}

char *args[MAXARG + 1];
int at = 0;

if (!strcmp(argv[1], "-n")) { // xargs -n 1 ...
for (int i = 3; i < argc; ++i) {
args[at] = malloc(sizeof argv[i]);
memcpy(args[at++], argv[i], sizeof argv[i]);
}
args[at] = malloc(24); // assume max length 24
char *pargs[MAXARG];
int t = fmtpargs(pargs, buf, n); // pargs[0...t]
for (int i = 0; i < t; ++i) {
memcpy(args[at], pargs[i], sizeof pargs[i]);
if (fork() == 0) {
exec(args[0], args);
exit(0);
} else {
wait(0);
}
}
} else {
for (int i = 1; i < argc; ++i) {
args[at] = malloc(sizeof argv[i]);
memcpy(args[at++], argv[i], sizeof argv[i]);
}
fmtsargs(args, at, buf, n);
exec(args[0], args);
}

exit(0);
}

0 comments on commit a1ceb89

Please sign in to comment.