Fun 0.41.5
The programming language that makes You have fun
Loading...
Searching...
No Matches
proc_run.c
Go to the documentation of this file.
1/*
2 * This file is part of the Fun programming language.
3 * https://fun-lang.xyz/
4 *
5 * Copyright 2025 Johannes Findeisen
6 * Licensed under the terms of the Apache-2.0 license.
7 * https://opensource.org/license/apache-2-0
8 */
9
21
22#include <stdio.h>
23#include <stdlib.h>
24#include <string.h>
25#ifdef _WIN32
26#define popen _popen
27#define pclose _pclose
28#endif
29
31 /* Pops command string; pushes map {"out": string, "code": int} */
32 Value cmdv = pop_value(vm);
33 char *cmd = value_to_string_alloc(&cmdv);
34 free_value(cmdv);
35 if (!cmd) {
37 map_set(&m, "out", make_string(""));
38 map_set(&m, "code", make_int(-1));
39 push_value(vm, m);
40 break;
41 }
42
43 /* Use popen to run via shell and capture stdout */
44 FILE *fp = popen(cmd, "r");
45 int exit_code = -1;
46 char *out = NULL;
47 size_t cap = 0, len = 0;
48 if (fp) {
49 cap = 4096;
50 out = (char *)malloc(cap);
51 if (!out) {
52 pclose(fp);
53 free(cmd);
55 map_set(&m, "out", make_string(""));
56 map_set(&m, "code", make_int(-1));
57 push_value(vm, m);
58 break;
59 }
60 int c;
61 while ((c = fgetc(fp)) != EOF) {
62 if (len + 1 >= cap) {
63 cap *= 2;
64 char *nb = (char *)realloc(out, cap);
65 if (!nb) {
66 free(out);
67 pclose(fp);
68 free(cmd);
70 map_set(&m, "out", make_string(""));
71 map_set(&m, "code", make_int(-1));
72 push_value(vm, m);
73 goto done_push;
74 }
75 out = nb;
76 }
77 out[len++] = (char)c;
78 }
79 out[len] = '\0';
80 int status = pclose(fp);
81#ifdef __unix__
82 if (WIFEXITED(status))
83 exit_code = WEXITSTATUS(status);
84 else
85 exit_code = -1;
86#else
88#endif
89 } else {
90 out = strdup("");
91 exit_code = -1;
92 }
93
95 map_set(&m, "out", make_string(out ? out : ""));
98
99done_push:
100 if (out) free(out);
102 break;
103}
Value out
Definition apop.c:38
@ OP_PROC_RUN
Definition bytecode.h:142
vm exit_code
Definition exit.c:37
Value m
Definition has_key.c:27
size_t len
Definition input_line.c:102
size_t cap
Definition input_line.c:101
Value c
Definition load_const.c:31
int map_set(Value *vm, const char *key, Value v)
Insert or replace a key in the map.
Definition map.c:79
Value make_map_empty(void)
Construct a new empty map Value.
Definition map.c:35
free_value(cmdv)
push_value(vm, m)
free(cmd)
char * cmd
Definition proc_run.c:33
int status
Definition proc_system.c:30
Tagged union representing a Fun value.
Definition value.h:68
vm fp
Definition throw.c:57
Value make_string(const char *s)
Construct a string Value by duplicating the given C string.
Definition value.c:95
char * value_to_string_alloc(const Value *v)
Allocate a printable C string for a Value.
Definition value.c:641
Value make_int(int64_t v)
Construct a Value representing a 64-bit integer.
Definition value.c:51