summaryrefslogtreecommitdiff
path: root/user/xargs.c
diff options
context:
space:
mode:
authorMole Shang <[email protected]>2024-01-17 11:33:39 +0800
committerMole Shang <[email protected]>2024-01-17 11:33:39 +0800
commitdaa90a639a35e9f99747c92bb28946ac414615bd (patch)
treecc119f4e037015b2fdff2b4ed8d989b8db66e3b0 /user/xargs.c
parentc424f997808269559f7968c812860fd1f1974a13 (diff)
downloadxv6-labs-util.tar.gz
xv6-labs-util.tar.bz2
xv6-labs-util.zip
lab util: finishutil
Diffstat (limited to 'user/xargs.c')
-rw-r--r--user/xargs.c60
1 files changed, 60 insertions, 0 deletions
diff --git a/user/xargs.c b/user/xargs.c
new file mode 100644
index 0000000..b5b9bee
--- /dev/null
+++ b/user/xargs.c
@@ -0,0 +1,60 @@
+#include "kernel/types.h"
+
+#include "kernel/param.h"
+#include "kernel/stat.h"
+#include "user/user.h"
+
+#define is_blank(chr) (chr == ' ' || chr == '\t')
+
+int
+main(int argc, char* argv[])
+{
+ char buf[2048], ch;
+ char* p = buf;
+ char* v[MAXARG];
+ int c;
+ int blanks = 0;
+ int offset = 0;
+
+ if (argc <= 1) {
+ fprintf(2, "usage: xargs <command> [argv...]\n");
+ exit(1);
+ }
+
+ for (c = 1; c < argc; c++) {
+ v[c - 1] = argv[c];
+ }
+ --c;
+
+ while (read(0, &ch, 1) > 0) {
+ if (is_blank(ch)) {
+ blanks++;
+ continue;
+ }
+
+ if (blanks) {
+ buf[offset++] = 0;
+
+ v[c++] = p;
+ p = buf + offset;
+
+ blanks = 0;
+ }
+
+ if (ch != '\n') {
+ buf[offset++] = ch;
+ } else {
+ v[c++] = p;
+ p = buf + offset;
+
+ if (!fork()) {
+ exit(exec(v[0], v));
+ }
+ wait(0);
+
+ c = argc - 1;
+ }
+ }
+
+ exit(0);
+}