* alloc.c: Do not define struct catchtag.
[bpt/emacs.git] / src / process.c
1 /* Asynchronous subprocess control for GNU Emacs.
2 Copyright (C) 1985, 1986, 1987, 1988, 1993, 1994, 1995,
3 1996, 1998, 1999, 2001, 2002, 2003, 2004,
4 2005, 2006, 2007, 2008, 2009 Free Software Foundation, Inc.
5
6 This file is part of GNU Emacs.
7
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
12
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
20
21
22 #include <config.h>
23 #include <signal.h>
24
25 /* This file is split into two parts by the following preprocessor
26 conditional. The 'then' clause contains all of the support for
27 asynchronous subprocesses. The 'else' clause contains stub
28 versions of some of the asynchronous subprocess routines that are
29 often called elsewhere in Emacs, so we don't have to #ifdef the
30 sections that call them. */
31
32 \f
33 #ifdef subprocesses
34
35 #include <stdio.h>
36 #include <errno.h>
37 #include <setjmp.h>
38 #include <sys/types.h> /* some typedefs are used in sys/file.h */
39 #include <sys/file.h>
40 #include <sys/stat.h>
41 #include <setjmp.h>
42 #ifdef HAVE_INTTYPES_H
43 #include <inttypes.h>
44 #endif
45 #ifdef STDC_HEADERS
46 #include <stdlib.h>
47 #endif
48
49 #ifdef HAVE_UNISTD_H
50 #include <unistd.h>
51 #endif
52 #include <fcntl.h>
53
54 #ifdef HAVE_SOCKETS /* TCP connection support, if kernel can do it */
55 #include <sys/socket.h>
56 #include <netdb.h>
57 #include <netinet/in.h>
58 #include <arpa/inet.h>
59
60 /* Are local (unix) sockets supported? */
61 #if defined (HAVE_SYS_UN_H)
62 #if !defined (AF_LOCAL) && defined (AF_UNIX)
63 #define AF_LOCAL AF_UNIX
64 #endif
65 #ifdef AF_LOCAL
66 #define HAVE_LOCAL_SOCKETS
67 #include <sys/un.h>
68 #endif
69 #endif
70 #endif /* HAVE_SOCKETS */
71
72 #if defined(BSD_SYSTEM)
73 #include <sys/ioctl.h>
74 #if !defined (O_NDELAY) && defined (HAVE_PTYS) && !defined(USG5)
75 #include <fcntl.h>
76 #endif /* HAVE_PTYS and no O_NDELAY */
77 #endif /* BSD_SYSTEM */
78
79 #ifdef NEED_BSDTTY
80 #include <bsdtty.h>
81 #endif
82
83 /* Can we use SIOCGIFCONF and/or SIOCGIFADDR */
84 #ifdef HAVE_SOCKETS
85 #if defined(HAVE_SYS_IOCTL_H) && defined(HAVE_NET_IF_H)
86 /* sys/ioctl.h may have been included already */
87 #ifndef SIOCGIFADDR
88 #include <sys/ioctl.h>
89 #endif
90 #include <net/if.h>
91 #endif
92 #endif
93
94 #ifdef HAVE_SYS_WAIT
95 #include <sys/wait.h>
96 #endif
97
98 #ifdef HAVE_RES_INIT
99 #include <netinet/in.h>
100 #include <arpa/nameser.h>
101 #include <resolv.h>
102 #endif
103
104 #include "lisp.h"
105 #include "systime.h"
106 #include "systty.h"
107
108 #include "window.h"
109 #include "buffer.h"
110 #include "character.h"
111 #include "coding.h"
112 #include "process.h"
113 #include "frame.h"
114 #include "termhooks.h"
115 #include "termopts.h"
116 #include "commands.h"
117 #include "keyboard.h"
118 #include "blockinput.h"
119 #include "dispextern.h"
120 #include "composite.h"
121 #include "atimer.h"
122
123 Lisp_Object Qprocessp;
124 Lisp_Object Qrun, Qstop, Qsignal;
125 Lisp_Object Qopen, Qclosed, Qconnect, Qfailed, Qlisten;
126 Lisp_Object Qlocal, Qipv4, Qdatagram;
127 Lisp_Object Qreal, Qnetwork, Qserial;
128 #ifdef AF_INET6
129 Lisp_Object Qipv6;
130 #endif
131 Lisp_Object QCport, QCspeed, QCprocess;
132 Lisp_Object QCbytesize, QCstopbits, QCparity, Qodd, Qeven;
133 Lisp_Object QCflowcontrol, Qhw, Qsw, QCsummary;
134 Lisp_Object QCname, QCbuffer, QChost, QCservice, QCtype;
135 Lisp_Object QClocal, QCremote, QCcoding;
136 Lisp_Object QCserver, QCnowait, QCnoquery, QCstop;
137 Lisp_Object QCsentinel, QClog, QCoptions, QCplist;
138 Lisp_Object Qlast_nonmenu_event;
139 /* QCfamily is declared and initialized in xfaces.c,
140 QCfilter in keyboard.c. */
141 extern Lisp_Object QCfamily, QCfilter;
142
143 /* Qexit is declared and initialized in eval.c. */
144
145 /* QCfamily is defined in xfaces.c. */
146 extern Lisp_Object QCfamily;
147 /* QCfilter is defined in keyboard.c. */
148 extern Lisp_Object QCfilter;
149
150 Lisp_Object Qeuid, Qegid, Qcomm, Qstate, Qppid, Qpgrp, Qsess, Qttname, Qtpgid;
151 Lisp_Object Qminflt, Qmajflt, Qcminflt, Qcmajflt, Qutime, Qstime, Qcstime;
152 Lisp_Object Qcutime, Qpri, Qnice, Qthcount, Qstart, Qvsize, Qrss, Qargs;
153 Lisp_Object Quser, Qgroup, Qetime, Qpcpu, Qpmem, Qtime, Qctime;
154
155 #ifdef HAVE_SOCKETS
156 #define NETCONN_P(p) (EQ (XPROCESS (p)->type, Qnetwork))
157 #define NETCONN1_P(p) (EQ ((p)->type, Qnetwork))
158 #define SERIALCONN_P(p) (EQ (XPROCESS (p)->type, Qserial))
159 #define SERIALCONN1_P(p) (EQ ((p)->type, Qserial))
160 #else
161 #define NETCONN_P(p) 0
162 #define NETCONN1_P(p) 0
163 #define SERIALCONN_P(p) 0
164 #define SERIALCONN1_P(p) 0
165 #endif /* HAVE_SOCKETS */
166
167 /* Define first descriptor number available for subprocesses. */
168 #define FIRST_PROC_DESC 3
169
170 /* Define SIGCHLD as an alias for SIGCLD. There are many conditionals
171 testing SIGCHLD. */
172
173 #if !defined (SIGCHLD) && defined (SIGCLD)
174 #define SIGCHLD SIGCLD
175 #endif /* SIGCLD */
176
177 #include "syssignal.h"
178
179 #include "syswait.h"
180
181 extern char *get_operating_system_release ();
182
183 /* Serial processes require termios or Windows. */
184 #if defined (HAVE_TERMIOS) || defined (WINDOWSNT)
185 #define HAVE_SERIAL
186 #endif
187
188 #ifdef HAVE_SERIAL
189 /* From sysdep.c or w32.c */
190 extern int serial_open (char *port);
191 extern void serial_configure (struct Lisp_Process *p, Lisp_Object contact);
192 #endif
193
194 #ifndef USE_CRT_DLL
195 extern int errno;
196 #endif
197
198 #ifndef HAVE_H_ERRNO
199 extern int h_errno;
200 #endif
201
202 /* t means use pty, nil means use a pipe,
203 maybe other values to come. */
204 static Lisp_Object Vprocess_connection_type;
205
206 /* These next two vars are non-static since sysdep.c uses them in the
207 emulation of `select'. */
208 /* Number of events of change of status of a process. */
209 int process_tick;
210 /* Number of events for which the user or sentinel has been notified. */
211 int update_tick;
212
213 /* Define NON_BLOCKING_CONNECT if we can support non-blocking connects. */
214
215 #ifdef BROKEN_NON_BLOCKING_CONNECT
216 #undef NON_BLOCKING_CONNECT
217 #else
218 #ifndef NON_BLOCKING_CONNECT
219 #ifdef HAVE_SOCKETS
220 #ifdef HAVE_SELECT
221 #if defined (HAVE_GETPEERNAME) || defined (GNU_LINUX)
222 #if defined (O_NONBLOCK) || defined (O_NDELAY)
223 #if defined (EWOULDBLOCK) || defined (EINPROGRESS)
224 #define NON_BLOCKING_CONNECT
225 #endif /* EWOULDBLOCK || EINPROGRESS */
226 #endif /* O_NONBLOCK || O_NDELAY */
227 #endif /* HAVE_GETPEERNAME || GNU_LINUX */
228 #endif /* HAVE_SELECT */
229 #endif /* HAVE_SOCKETS */
230 #endif /* NON_BLOCKING_CONNECT */
231 #endif /* BROKEN_NON_BLOCKING_CONNECT */
232
233 /* Define DATAGRAM_SOCKETS if datagrams can be used safely on
234 this system. We need to read full packets, so we need a
235 "non-destructive" select. So we require either native select,
236 or emulation of select using FIONREAD. */
237
238 #ifdef BROKEN_DATAGRAM_SOCKETS
239 #undef DATAGRAM_SOCKETS
240 #else
241 #ifndef DATAGRAM_SOCKETS
242 #ifdef HAVE_SOCKETS
243 #if defined (HAVE_SELECT) || defined (FIONREAD)
244 #if defined (HAVE_SENDTO) && defined (HAVE_RECVFROM) && defined (EMSGSIZE)
245 #define DATAGRAM_SOCKETS
246 #endif /* HAVE_SENDTO && HAVE_RECVFROM && EMSGSIZE */
247 #endif /* HAVE_SELECT || FIONREAD */
248 #endif /* HAVE_SOCKETS */
249 #endif /* DATAGRAM_SOCKETS */
250 #endif /* BROKEN_DATAGRAM_SOCKETS */
251
252 #if !defined (ADAPTIVE_READ_BUFFERING) && !defined (NO_ADAPTIVE_READ_BUFFERING)
253 #ifdef EMACS_HAS_USECS
254 #define ADAPTIVE_READ_BUFFERING
255 #endif
256 #endif
257
258 #ifdef ADAPTIVE_READ_BUFFERING
259 #define READ_OUTPUT_DELAY_INCREMENT 10000
260 #define READ_OUTPUT_DELAY_MAX (READ_OUTPUT_DELAY_INCREMENT * 5)
261 #define READ_OUTPUT_DELAY_MAX_MAX (READ_OUTPUT_DELAY_INCREMENT * 7)
262
263 /* Number of processes which have a non-zero read_output_delay,
264 and therefore might be delayed for adaptive read buffering. */
265
266 static int process_output_delay_count;
267
268 /* Non-zero if any process has non-nil read_output_skip. */
269
270 static int process_output_skip;
271
272 /* Non-nil means to delay reading process output to improve buffering.
273 A value of t means that delay is reset after each send, any other
274 non-nil value does not reset the delay. A value of nil disables
275 adaptive read buffering completely. */
276 static Lisp_Object Vprocess_adaptive_read_buffering;
277 #else
278 #define process_output_delay_count 0
279 #endif
280
281
282 #include "sysselect.h"
283
284 static int keyboard_bit_set P_ ((SELECT_TYPE *));
285 static void deactivate_process P_ ((Lisp_Object));
286 static void status_notify P_ ((struct Lisp_Process *));
287 static int read_process_output P_ ((Lisp_Object, int));
288 static void create_pty P_ ((Lisp_Object));
289
290 /* If we support a window system, turn on the code to poll periodically
291 to detect C-g. It isn't actually used when doing interrupt input. */
292 #ifdef HAVE_WINDOW_SYSTEM
293 #define POLL_FOR_INPUT
294 #endif
295
296 static Lisp_Object get_process ();
297 static void exec_sentinel ();
298
299 extern EMACS_TIME timer_check ();
300 extern int timers_run;
301 \f
302 /* Mask of bits indicating the descriptors that we wait for input on. */
303
304 static SELECT_TYPE input_wait_mask;
305
306 /* Mask that excludes keyboard input descriptor(s). */
307
308 static SELECT_TYPE non_keyboard_wait_mask;
309
310 /* Mask that excludes process input descriptor(s). */
311
312 static SELECT_TYPE non_process_wait_mask;
313
314 /* Mask for the gpm mouse input descriptor. */
315
316 static SELECT_TYPE gpm_wait_mask;
317
318 #ifdef NON_BLOCKING_CONNECT
319 /* Mask of bits indicating the descriptors that we wait for connect to
320 complete on. Once they complete, they are removed from this mask
321 and added to the input_wait_mask and non_keyboard_wait_mask. */
322
323 static SELECT_TYPE connect_wait_mask;
324
325 /* Number of bits set in connect_wait_mask. */
326 static int num_pending_connects;
327
328 #define IF_NON_BLOCKING_CONNECT(s) s
329 #else
330 #define IF_NON_BLOCKING_CONNECT(s)
331 #endif
332
333 /* The largest descriptor currently in use for a process object. */
334 static int max_process_desc;
335
336 /* The largest descriptor currently in use for keyboard input. */
337 static int max_keyboard_desc;
338
339 /* The largest descriptor currently in use for gpm mouse input. */
340 static int max_gpm_desc;
341
342 /* Nonzero means delete a process right away if it exits. */
343 static int delete_exited_processes;
344
345 /* Indexed by descriptor, gives the process (if any) for that descriptor */
346 Lisp_Object chan_process[MAXDESC];
347
348 /* Alist of elements (NAME . PROCESS) */
349 Lisp_Object Vprocess_alist;
350
351 /* Buffered-ahead input char from process, indexed by channel.
352 -1 means empty (no char is buffered).
353 Used on sys V where the only way to tell if there is any
354 output from the process is to read at least one char.
355 Always -1 on systems that support FIONREAD. */
356
357 /* Don't make static; need to access externally. */
358 int proc_buffered_char[MAXDESC];
359
360 /* Table of `struct coding-system' for each process. */
361 static struct coding_system *proc_decode_coding_system[MAXDESC];
362 static struct coding_system *proc_encode_coding_system[MAXDESC];
363
364 #ifdef DATAGRAM_SOCKETS
365 /* Table of `partner address' for datagram sockets. */
366 struct sockaddr_and_len {
367 struct sockaddr *sa;
368 int len;
369 } datagram_address[MAXDESC];
370 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
371 #define DATAGRAM_CONN_P(proc) (PROCESSP (proc) && datagram_address[XPROCESS (proc)->infd].sa != 0)
372 #else
373 #define DATAGRAM_CHAN_P(chan) (0)
374 #define DATAGRAM_CONN_P(proc) (0)
375 #endif
376
377 /* Maximum number of bytes to send to a pty without an eof. */
378 static int pty_max_bytes;
379
380 /* Nonzero means don't run process sentinels. This is used
381 when exiting. */
382 int inhibit_sentinels;
383
384 #ifdef HAVE_PTYS
385 #ifdef HAVE_PTY_H
386 #include <pty.h>
387 #endif
388 /* The file name of the pty opened by allocate_pty. */
389
390 static char pty_name[24];
391 #endif
392 \f
393 /* Compute the Lisp form of the process status, p->status, from
394 the numeric status that was returned by `wait'. */
395
396 static Lisp_Object status_convert (int);
397
398 static void
399 update_status (p)
400 struct Lisp_Process *p;
401 {
402 eassert (p->raw_status_new);
403 p->status = status_convert (p->raw_status);
404 p->raw_status_new = 0;
405 }
406
407 /* Convert a process status word in Unix format to
408 the list that we use internally. */
409
410 static Lisp_Object
411 status_convert (int w)
412 {
413 if (WIFSTOPPED (w))
414 return Fcons (Qstop, Fcons (make_number (WSTOPSIG (w)), Qnil));
415 else if (WIFEXITED (w))
416 return Fcons (Qexit, Fcons (make_number (WRETCODE (w)),
417 WCOREDUMP (w) ? Qt : Qnil));
418 else if (WIFSIGNALED (w))
419 return Fcons (Qsignal, Fcons (make_number (WTERMSIG (w)),
420 WCOREDUMP (w) ? Qt : Qnil));
421 else
422 return Qrun;
423 }
424
425 /* Given a status-list, extract the three pieces of information
426 and store them individually through the three pointers. */
427
428 static void
429 decode_status (l, symbol, code, coredump)
430 Lisp_Object l;
431 Lisp_Object *symbol;
432 int *code;
433 int *coredump;
434 {
435 Lisp_Object tem;
436
437 if (SYMBOLP (l))
438 {
439 *symbol = l;
440 *code = 0;
441 *coredump = 0;
442 }
443 else
444 {
445 *symbol = XCAR (l);
446 tem = XCDR (l);
447 *code = XFASTINT (XCAR (tem));
448 tem = XCDR (tem);
449 *coredump = !NILP (tem);
450 }
451 }
452
453 /* Return a string describing a process status list. */
454
455 static Lisp_Object
456 status_message (p)
457 struct Lisp_Process *p;
458 {
459 Lisp_Object status = p->status;
460 Lisp_Object symbol;
461 int code, coredump;
462 Lisp_Object string, string2;
463
464 decode_status (status, &symbol, &code, &coredump);
465
466 if (EQ (symbol, Qsignal) || EQ (symbol, Qstop))
467 {
468 char *signame;
469 synchronize_system_messages_locale ();
470 signame = strsignal (code);
471 if (signame == 0)
472 string = build_string ("unknown");
473 else
474 {
475 int c1, c2;
476
477 string = make_unibyte_string (signame, strlen (signame));
478 if (! NILP (Vlocale_coding_system))
479 string = (code_convert_string_norecord
480 (string, Vlocale_coding_system, 0));
481 c1 = STRING_CHAR ((char *) SDATA (string), 0);
482 c2 = DOWNCASE (c1);
483 if (c1 != c2)
484 Faset (string, make_number (0), make_number (c2));
485 }
486 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
487 return concat2 (string, string2);
488 }
489 else if (EQ (symbol, Qexit))
490 {
491 if (NETCONN1_P (p))
492 return build_string (code == 0 ? "deleted\n" : "connection broken by remote peer\n");
493 if (code == 0)
494 return build_string ("finished\n");
495 string = Fnumber_to_string (make_number (code));
496 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
497 return concat3 (build_string ("exited abnormally with code "),
498 string, string2);
499 }
500 else if (EQ (symbol, Qfailed))
501 {
502 string = Fnumber_to_string (make_number (code));
503 string2 = build_string ("\n");
504 return concat3 (build_string ("failed with code "),
505 string, string2);
506 }
507 else
508 return Fcopy_sequence (Fsymbol_name (symbol));
509 }
510 \f
511 #ifdef HAVE_PTYS
512
513 /* Open an available pty, returning a file descriptor.
514 Return -1 on failure.
515 The file name of the terminal corresponding to the pty
516 is left in the variable pty_name. */
517
518 static int
519 allocate_pty ()
520 {
521 register int c, i;
522 int fd;
523
524 #ifdef PTY_ITERATION
525 PTY_ITERATION
526 #else
527 for (c = FIRST_PTY_LETTER; c <= 'z'; c++)
528 for (i = 0; i < 16; i++)
529 #endif
530 {
531 struct stat stb; /* Used in some PTY_OPEN. */
532 #ifdef PTY_NAME_SPRINTF
533 PTY_NAME_SPRINTF
534 #else
535 sprintf (pty_name, "/dev/pty%c%x", c, i);
536 #endif /* no PTY_NAME_SPRINTF */
537
538 #ifdef PTY_OPEN
539 PTY_OPEN;
540 #else /* no PTY_OPEN */
541 {
542 { /* Some systems name their pseudoterminals so that there are gaps in
543 the usual sequence - for example, on HP9000/S700 systems, there
544 are no pseudoterminals with names ending in 'f'. So we wait for
545 three failures in a row before deciding that we've reached the
546 end of the ptys. */
547 int failed_count = 0;
548
549 if (stat (pty_name, &stb) < 0)
550 {
551 failed_count++;
552 if (failed_count >= 3)
553 return -1;
554 }
555 else
556 failed_count = 0;
557 }
558 # ifdef O_NONBLOCK
559 fd = emacs_open (pty_name, O_RDWR | O_NONBLOCK, 0);
560 # else
561 fd = emacs_open (pty_name, O_RDWR | O_NDELAY, 0);
562 # endif
563 }
564 #endif /* no PTY_OPEN */
565
566 if (fd >= 0)
567 {
568 /* check to make certain that both sides are available
569 this avoids a nasty yet stupid bug in rlogins */
570 #ifdef PTY_TTY_NAME_SPRINTF
571 PTY_TTY_NAME_SPRINTF
572 #else
573 sprintf (pty_name, "/dev/tty%c%x", c, i);
574 #endif /* no PTY_TTY_NAME_SPRINTF */
575 if (access (pty_name, 6) != 0)
576 {
577 emacs_close (fd);
578 # ifndef __sgi
579 continue;
580 # else
581 return -1;
582 # endif /* __sgi */
583 }
584 setup_pty (fd);
585 return fd;
586 }
587 }
588 return -1;
589 }
590 #endif /* HAVE_PTYS */
591 \f
592 static Lisp_Object
593 make_process (name)
594 Lisp_Object name;
595 {
596 register Lisp_Object val, tem, name1;
597 register struct Lisp_Process *p;
598 char suffix[10];
599 register int i;
600
601 p = allocate_process ();
602
603 p->infd = -1;
604 p->outfd = -1;
605 p->tick = 0;
606 p->update_tick = 0;
607 p->pid = 0;
608 p->pty_flag = 0;
609 p->raw_status_new = 0;
610 p->status = Qrun;
611 p->mark = Fmake_marker ();
612 p->kill_without_query = 0;
613
614 #ifdef ADAPTIVE_READ_BUFFERING
615 p->adaptive_read_buffering = 0;
616 p->read_output_delay = 0;
617 p->read_output_skip = 0;
618 #endif
619
620 /* If name is already in use, modify it until it is unused. */
621
622 name1 = name;
623 for (i = 1; ; i++)
624 {
625 tem = Fget_process (name1);
626 if (NILP (tem)) break;
627 sprintf (suffix, "<%d>", i);
628 name1 = concat2 (name, build_string (suffix));
629 }
630 name = name1;
631 p->name = name;
632 XSETPROCESS (val, p);
633 Vprocess_alist = Fcons (Fcons (name, val), Vprocess_alist);
634 return val;
635 }
636
637 static void
638 remove_process (proc)
639 register Lisp_Object proc;
640 {
641 register Lisp_Object pair;
642
643 pair = Frassq (proc, Vprocess_alist);
644 Vprocess_alist = Fdelq (pair, Vprocess_alist);
645
646 deactivate_process (proc);
647 }
648
649 /* Setup coding systems of PROCESS. */
650
651 void
652 setup_process_coding_systems (process)
653 Lisp_Object process;
654 {
655 struct Lisp_Process *p = XPROCESS (process);
656 int inch = p->infd;
657 int outch = p->outfd;
658 Lisp_Object coding_system;
659
660 if (inch < 0 || outch < 0)
661 return;
662
663 if (!proc_decode_coding_system[inch])
664 proc_decode_coding_system[inch]
665 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
666 coding_system = p->decode_coding_system;
667 if (! NILP (p->filter))
668 ;
669 else if (BUFFERP (p->buffer))
670 {
671 if (NILP (XBUFFER (p->buffer)->enable_multibyte_characters))
672 coding_system = raw_text_coding_system (coding_system);
673 }
674 setup_coding_system (coding_system, proc_decode_coding_system[inch]);
675
676 if (!proc_encode_coding_system[outch])
677 proc_encode_coding_system[outch]
678 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
679 setup_coding_system (p->encode_coding_system,
680 proc_encode_coding_system[outch]);
681 }
682 \f
683 DEFUN ("processp", Fprocessp, Sprocessp, 1, 1, 0,
684 doc: /* Return t if OBJECT is a process. */)
685 (object)
686 Lisp_Object object;
687 {
688 return PROCESSP (object) ? Qt : Qnil;
689 }
690
691 DEFUN ("get-process", Fget_process, Sget_process, 1, 1, 0,
692 doc: /* Return the process named NAME, or nil if there is none. */)
693 (name)
694 register Lisp_Object name;
695 {
696 if (PROCESSP (name))
697 return name;
698 CHECK_STRING (name);
699 return Fcdr (Fassoc (name, Vprocess_alist));
700 }
701
702 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
703 doc: /* Return the (or a) process associated with BUFFER.
704 BUFFER may be a buffer or the name of one. */)
705 (buffer)
706 register Lisp_Object buffer;
707 {
708 register Lisp_Object buf, tail, proc;
709
710 if (NILP (buffer)) return Qnil;
711 buf = Fget_buffer (buffer);
712 if (NILP (buf)) return Qnil;
713
714 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
715 {
716 proc = Fcdr (XCAR (tail));
717 if (PROCESSP (proc) && EQ (XPROCESS (proc)->buffer, buf))
718 return proc;
719 }
720 return Qnil;
721 }
722
723 /* This is how commands for the user decode process arguments. It
724 accepts a process, a process name, a buffer, a buffer name, or nil.
725 Buffers denote the first process in the buffer, and nil denotes the
726 current buffer. */
727
728 static Lisp_Object
729 get_process (name)
730 register Lisp_Object name;
731 {
732 register Lisp_Object proc, obj;
733 if (STRINGP (name))
734 {
735 obj = Fget_process (name);
736 if (NILP (obj))
737 obj = Fget_buffer (name);
738 if (NILP (obj))
739 error ("Process %s does not exist", SDATA (name));
740 }
741 else if (NILP (name))
742 obj = Fcurrent_buffer ();
743 else
744 obj = name;
745
746 /* Now obj should be either a buffer object or a process object.
747 */
748 if (BUFFERP (obj))
749 {
750 proc = Fget_buffer_process (obj);
751 if (NILP (proc))
752 error ("Buffer %s has no process", SDATA (XBUFFER (obj)->name));
753 }
754 else
755 {
756 CHECK_PROCESS (obj);
757 proc = obj;
758 }
759 return proc;
760 }
761
762
763 #ifdef SIGCHLD
764 /* Fdelete_process promises to immediately forget about the process, but in
765 reality, Emacs needs to remember those processes until they have been
766 treated by sigchld_handler; otherwise this handler would consider the
767 process as being synchronous and say that the synchronous process is
768 dead. */
769 static Lisp_Object deleted_pid_list;
770 #endif
771
772 DEFUN ("delete-process", Fdelete_process, Sdelete_process, 1, 1, 0,
773 doc: /* Delete PROCESS: kill it and forget about it immediately.
774 PROCESS may be a process, a buffer, the name of a process or buffer, or
775 nil, indicating the current buffer's process. */)
776 (process)
777 register Lisp_Object process;
778 {
779 register struct Lisp_Process *p;
780
781 process = get_process (process);
782 p = XPROCESS (process);
783
784 p->raw_status_new = 0;
785 if (NETCONN1_P (p) || SERIALCONN1_P (p))
786 {
787 p->status = Fcons (Qexit, Fcons (make_number (0), Qnil));
788 p->tick = ++process_tick;
789 status_notify (p);
790 redisplay_preserve_echo_area (13);
791 }
792 else if (p->infd >= 0)
793 {
794 #ifdef SIGCHLD
795 Lisp_Object symbol;
796 /* Assignment to EMACS_INT stops GCC whining about limited range
797 of data type. */
798 EMACS_INT pid = p->pid;
799
800 /* No problem storing the pid here, as it is still in Vprocess_alist. */
801 deleted_pid_list = Fcons (make_fixnum_or_float (pid),
802 /* GC treated elements set to nil. */
803 Fdelq (Qnil, deleted_pid_list));
804 /* If the process has already signaled, remove it from the list. */
805 if (p->raw_status_new)
806 update_status (p);
807 symbol = p->status;
808 if (CONSP (p->status))
809 symbol = XCAR (p->status);
810 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit))
811 deleted_pid_list
812 = Fdelete (make_fixnum_or_float (pid), deleted_pid_list);
813 else
814 #endif
815 {
816 Fkill_process (process, Qnil);
817 /* Do this now, since remove_process will make sigchld_handler do nothing. */
818 p->status
819 = Fcons (Qsignal, Fcons (make_number (SIGKILL), Qnil));
820 p->tick = ++process_tick;
821 status_notify (p);
822 redisplay_preserve_echo_area (13);
823 }
824 }
825 remove_process (process);
826 return Qnil;
827 }
828 \f
829 DEFUN ("process-status", Fprocess_status, Sprocess_status, 1, 1, 0,
830 doc: /* Return the status of PROCESS.
831 The returned value is one of the following symbols:
832 run -- for a process that is running.
833 stop -- for a process stopped but continuable.
834 exit -- for a process that has exited.
835 signal -- for a process that has got a fatal signal.
836 open -- for a network stream connection that is open.
837 listen -- for a network stream server that is listening.
838 closed -- for a network stream connection that is closed.
839 connect -- when waiting for a non-blocking connection to complete.
840 failed -- when a non-blocking connection has failed.
841 nil -- if arg is a process name and no such process exists.
842 PROCESS may be a process, a buffer, the name of a process, or
843 nil, indicating the current buffer's process. */)
844 (process)
845 register Lisp_Object process;
846 {
847 register struct Lisp_Process *p;
848 register Lisp_Object status;
849
850 if (STRINGP (process))
851 process = Fget_process (process);
852 else
853 process = get_process (process);
854
855 if (NILP (process))
856 return process;
857
858 p = XPROCESS (process);
859 if (p->raw_status_new)
860 update_status (p);
861 status = p->status;
862 if (CONSP (status))
863 status = XCAR (status);
864 if (NETCONN1_P (p) || SERIALCONN1_P (p))
865 {
866 if (EQ (status, Qexit))
867 status = Qclosed;
868 else if (EQ (p->command, Qt))
869 status = Qstop;
870 else if (EQ (status, Qrun))
871 status = Qopen;
872 }
873 return status;
874 }
875
876 DEFUN ("process-exit-status", Fprocess_exit_status, Sprocess_exit_status,
877 1, 1, 0,
878 doc: /* Return the exit status of PROCESS or the signal number that killed it.
879 If PROCESS has not yet exited or died, return 0. */)
880 (process)
881 register Lisp_Object process;
882 {
883 CHECK_PROCESS (process);
884 if (XPROCESS (process)->raw_status_new)
885 update_status (XPROCESS (process));
886 if (CONSP (XPROCESS (process)->status))
887 return XCAR (XCDR (XPROCESS (process)->status));
888 return make_number (0);
889 }
890
891 DEFUN ("process-id", Fprocess_id, Sprocess_id, 1, 1, 0,
892 doc: /* Return the process id of PROCESS.
893 This is the pid of the external process which PROCESS uses or talks to.
894 For a network connection, this value is nil. */)
895 (process)
896 register Lisp_Object process;
897 {
898 /* Assignment to EMACS_INT stops GCC whining about limited range of
899 data type. */
900 EMACS_INT pid;
901
902 CHECK_PROCESS (process);
903 pid = XPROCESS (process)->pid;
904 return (pid ? make_fixnum_or_float (pid) : Qnil);
905 }
906
907 DEFUN ("process-name", Fprocess_name, Sprocess_name, 1, 1, 0,
908 doc: /* Return the name of PROCESS, as a string.
909 This is the name of the program invoked in PROCESS,
910 possibly modified to make it unique among process names. */)
911 (process)
912 register Lisp_Object process;
913 {
914 CHECK_PROCESS (process);
915 return XPROCESS (process)->name;
916 }
917
918 DEFUN ("process-command", Fprocess_command, Sprocess_command, 1, 1, 0,
919 doc: /* Return the command that was executed to start PROCESS.
920 This is a list of strings, the first string being the program executed
921 and the rest of the strings being the arguments given to it.
922 For a network or serial process, this is nil (process is running) or t
923 \(process is stopped). */)
924 (process)
925 register Lisp_Object process;
926 {
927 CHECK_PROCESS (process);
928 return XPROCESS (process)->command;
929 }
930
931 DEFUN ("process-tty-name", Fprocess_tty_name, Sprocess_tty_name, 1, 1, 0,
932 doc: /* Return the name of the terminal PROCESS uses, or nil if none.
933 This is the terminal that the process itself reads and writes on,
934 not the name of the pty that Emacs uses to talk with that terminal. */)
935 (process)
936 register Lisp_Object process;
937 {
938 CHECK_PROCESS (process);
939 return XPROCESS (process)->tty_name;
940 }
941
942 DEFUN ("set-process-buffer", Fset_process_buffer, Sset_process_buffer,
943 2, 2, 0,
944 doc: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil). */)
945 (process, buffer)
946 register Lisp_Object process, buffer;
947 {
948 struct Lisp_Process *p;
949
950 CHECK_PROCESS (process);
951 if (!NILP (buffer))
952 CHECK_BUFFER (buffer);
953 p = XPROCESS (process);
954 p->buffer = buffer;
955 if (NETCONN1_P (p) || SERIALCONN1_P (p))
956 p->childp = Fplist_put (p->childp, QCbuffer, buffer);
957 setup_process_coding_systems (process);
958 return buffer;
959 }
960
961 DEFUN ("process-buffer", Fprocess_buffer, Sprocess_buffer,
962 1, 1, 0,
963 doc: /* Return the buffer PROCESS is associated with.
964 Output from PROCESS is inserted in this buffer unless PROCESS has a filter. */)
965 (process)
966 register Lisp_Object process;
967 {
968 CHECK_PROCESS (process);
969 return XPROCESS (process)->buffer;
970 }
971
972 DEFUN ("process-mark", Fprocess_mark, Sprocess_mark,
973 1, 1, 0,
974 doc: /* Return the marker for the end of the last output from PROCESS. */)
975 (process)
976 register Lisp_Object process;
977 {
978 CHECK_PROCESS (process);
979 return XPROCESS (process)->mark;
980 }
981
982 DEFUN ("set-process-filter", Fset_process_filter, Sset_process_filter,
983 2, 2, 0,
984 doc: /* Give PROCESS the filter function FILTER; nil means no filter.
985 A value of t means stop accepting output from the process.
986
987 When a process has a filter, its buffer is not used for output.
988 Instead, each time it does output, the entire string of output is
989 passed to the filter.
990
991 The filter gets two arguments: the process and the string of output.
992 The string argument is normally a multibyte string, except:
993 - if the process' input coding system is no-conversion or raw-text,
994 it is a unibyte string (the non-converted input), or else
995 - if `default-enable-multibyte-characters' is nil, it is a unibyte
996 string (the result of converting the decoded input multibyte
997 string to unibyte with `string-make-unibyte'). */)
998 (process, filter)
999 register Lisp_Object process, filter;
1000 {
1001 struct Lisp_Process *p;
1002
1003 CHECK_PROCESS (process);
1004 p = XPROCESS (process);
1005
1006 /* Don't signal an error if the process' input file descriptor
1007 is closed. This could make debugging Lisp more difficult,
1008 for example when doing something like
1009
1010 (setq process (start-process ...))
1011 (debug)
1012 (set-process-filter process ...) */
1013
1014 if (p->infd >= 0)
1015 {
1016 if (EQ (filter, Qt) && !EQ (p->status, Qlisten))
1017 {
1018 FD_CLR (p->infd, &input_wait_mask);
1019 FD_CLR (p->infd, &non_keyboard_wait_mask);
1020 }
1021 else if (EQ (p->filter, Qt)
1022 /* Network or serial process not stopped: */
1023 && !EQ (p->command, Qt))
1024 {
1025 FD_SET (p->infd, &input_wait_mask);
1026 FD_SET (p->infd, &non_keyboard_wait_mask);
1027 }
1028 }
1029
1030 p->filter = filter;
1031 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1032 p->childp = Fplist_put (p->childp, QCfilter, filter);
1033 setup_process_coding_systems (process);
1034 return filter;
1035 }
1036
1037 DEFUN ("process-filter", Fprocess_filter, Sprocess_filter,
1038 1, 1, 0,
1039 doc: /* Returns the filter function of PROCESS; nil if none.
1040 See `set-process-filter' for more info on filter functions. */)
1041 (process)
1042 register Lisp_Object process;
1043 {
1044 CHECK_PROCESS (process);
1045 return XPROCESS (process)->filter;
1046 }
1047
1048 DEFUN ("set-process-sentinel", Fset_process_sentinel, Sset_process_sentinel,
1049 2, 2, 0,
1050 doc: /* Give PROCESS the sentinel SENTINEL; nil for none.
1051 The sentinel is called as a function when the process changes state.
1052 It gets two arguments: the process, and a string describing the change. */)
1053 (process, sentinel)
1054 register Lisp_Object process, sentinel;
1055 {
1056 struct Lisp_Process *p;
1057
1058 CHECK_PROCESS (process);
1059 p = XPROCESS (process);
1060
1061 p->sentinel = sentinel;
1062 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1063 p->childp = Fplist_put (p->childp, QCsentinel, sentinel);
1064 return sentinel;
1065 }
1066
1067 DEFUN ("process-sentinel", Fprocess_sentinel, Sprocess_sentinel,
1068 1, 1, 0,
1069 doc: /* Return the sentinel of PROCESS; nil if none.
1070 See `set-process-sentinel' for more info on sentinels. */)
1071 (process)
1072 register Lisp_Object process;
1073 {
1074 CHECK_PROCESS (process);
1075 return XPROCESS (process)->sentinel;
1076 }
1077
1078 DEFUN ("set-process-window-size", Fset_process_window_size,
1079 Sset_process_window_size, 3, 3, 0,
1080 doc: /* Tell PROCESS that it has logical window size HEIGHT and WIDTH. */)
1081 (process, height, width)
1082 register Lisp_Object process, height, width;
1083 {
1084 CHECK_PROCESS (process);
1085 CHECK_NATNUM (height);
1086 CHECK_NATNUM (width);
1087
1088 if (XPROCESS (process)->infd < 0
1089 || set_window_size (XPROCESS (process)->infd,
1090 XINT (height), XINT (width)) <= 0)
1091 return Qnil;
1092 else
1093 return Qt;
1094 }
1095
1096 DEFUN ("set-process-inherit-coding-system-flag",
1097 Fset_process_inherit_coding_system_flag,
1098 Sset_process_inherit_coding_system_flag, 2, 2, 0,
1099 doc: /* Determine whether buffer of PROCESS will inherit coding-system.
1100 If the second argument FLAG is non-nil, then the variable
1101 `buffer-file-coding-system' of the buffer associated with PROCESS
1102 will be bound to the value of the coding system used to decode
1103 the process output.
1104
1105 This is useful when the coding system specified for the process buffer
1106 leaves either the character code conversion or the end-of-line conversion
1107 unspecified, or if the coding system used to decode the process output
1108 is more appropriate for saving the process buffer.
1109
1110 Binding the variable `inherit-process-coding-system' to non-nil before
1111 starting the process is an alternative way of setting the inherit flag
1112 for the process which will run. */)
1113 (process, flag)
1114 register Lisp_Object process, flag;
1115 {
1116 CHECK_PROCESS (process);
1117 XPROCESS (process)->inherit_coding_system_flag = !NILP (flag);
1118 return flag;
1119 }
1120
1121 DEFUN ("process-inherit-coding-system-flag",
1122 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
1123 1, 1, 0,
1124 doc: /* Return the value of inherit-coding-system flag for PROCESS.
1125 If this flag is t, `buffer-file-coding-system' of the buffer
1126 associated with PROCESS will inherit the coding system used to decode
1127 the process output. */)
1128 (process)
1129 register Lisp_Object process;
1130 {
1131 CHECK_PROCESS (process);
1132 return XPROCESS (process)->inherit_coding_system_flag ? Qt : Qnil;
1133 }
1134
1135 DEFUN ("set-process-query-on-exit-flag",
1136 Fset_process_query_on_exit_flag, Sset_process_query_on_exit_flag,
1137 2, 2, 0,
1138 doc: /* Specify if query is needed for PROCESS when Emacs is exited.
1139 If the second argument FLAG is non-nil, Emacs will query the user before
1140 exiting or killing a buffer if PROCESS is running. */)
1141 (process, flag)
1142 register Lisp_Object process, flag;
1143 {
1144 CHECK_PROCESS (process);
1145 XPROCESS (process)->kill_without_query = NILP (flag);
1146 return flag;
1147 }
1148
1149 DEFUN ("process-query-on-exit-flag",
1150 Fprocess_query_on_exit_flag, Sprocess_query_on_exit_flag,
1151 1, 1, 0,
1152 doc: /* Return the current value of query-on-exit flag for PROCESS. */)
1153 (process)
1154 register Lisp_Object process;
1155 {
1156 CHECK_PROCESS (process);
1157 return (XPROCESS (process)->kill_without_query ? Qnil : Qt);
1158 }
1159
1160 #ifdef DATAGRAM_SOCKETS
1161 Lisp_Object Fprocess_datagram_address ();
1162 #endif
1163
1164 DEFUN ("process-contact", Fprocess_contact, Sprocess_contact,
1165 1, 2, 0,
1166 doc: /* Return the contact info of PROCESS; t for a real child.
1167 For a network or serial connection, the value depends on the optional
1168 KEY arg. If KEY is nil, value is a cons cell of the form (HOST
1169 SERVICE) for a network connection or (PORT SPEED) for a serial
1170 connection. If KEY is t, the complete contact information for the
1171 connection is returned, else the specific value for the keyword KEY is
1172 returned. See `make-network-process' or `make-serial-process' for a
1173 list of keywords. */)
1174 (process, key)
1175 register Lisp_Object process, key;
1176 {
1177 Lisp_Object contact;
1178
1179 CHECK_PROCESS (process);
1180 contact = XPROCESS (process)->childp;
1181
1182 #ifdef DATAGRAM_SOCKETS
1183 if (DATAGRAM_CONN_P (process)
1184 && (EQ (key, Qt) || EQ (key, QCremote)))
1185 contact = Fplist_put (contact, QCremote,
1186 Fprocess_datagram_address (process));
1187 #endif
1188
1189 if ((!NETCONN_P (process) && !SERIALCONN_P (process)) || EQ (key, Qt))
1190 return contact;
1191 if (NILP (key) && NETCONN_P (process))
1192 return Fcons (Fplist_get (contact, QChost),
1193 Fcons (Fplist_get (contact, QCservice), Qnil));
1194 if (NILP (key) && SERIALCONN_P (process))
1195 return Fcons (Fplist_get (contact, QCport),
1196 Fcons (Fplist_get (contact, QCspeed), Qnil));
1197 return Fplist_get (contact, key);
1198 }
1199
1200 DEFUN ("process-plist", Fprocess_plist, Sprocess_plist,
1201 1, 1, 0,
1202 doc: /* Return the plist of PROCESS. */)
1203 (process)
1204 register Lisp_Object process;
1205 {
1206 CHECK_PROCESS (process);
1207 return XPROCESS (process)->plist;
1208 }
1209
1210 DEFUN ("set-process-plist", Fset_process_plist, Sset_process_plist,
1211 2, 2, 0,
1212 doc: /* Replace the plist of PROCESS with PLIST. Returns PLIST. */)
1213 (process, plist)
1214 register Lisp_Object process, plist;
1215 {
1216 CHECK_PROCESS (process);
1217 CHECK_LIST (plist);
1218
1219 XPROCESS (process)->plist = plist;
1220 return plist;
1221 }
1222
1223 #if 0 /* Turned off because we don't currently record this info
1224 in the process. Perhaps add it. */
1225 DEFUN ("process-connection", Fprocess_connection, Sprocess_connection, 1, 1, 0,
1226 doc: /* Return the connection type of PROCESS.
1227 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1228 a socket connection. */)
1229 (process)
1230 Lisp_Object process;
1231 {
1232 return XPROCESS (process)->type;
1233 }
1234 #endif
1235
1236 DEFUN ("process-type", Fprocess_type, Sprocess_type, 1, 1, 0,
1237 doc: /* Return the connection type of PROCESS.
1238 The value is either the symbol `real', `network', or `serial'.
1239 PROCESS may be a process, a buffer, the name of a process or buffer, or
1240 nil, indicating the current buffer's process. */)
1241 (process)
1242 Lisp_Object process;
1243 {
1244 Lisp_Object proc;
1245 proc = get_process (process);
1246 return XPROCESS (proc)->type;
1247 }
1248
1249 #ifdef HAVE_SOCKETS
1250 DEFUN ("format-network-address", Fformat_network_address, Sformat_network_address,
1251 1, 2, 0,
1252 doc: /* Convert network ADDRESS from internal format to a string.
1253 A 4 or 5 element vector represents an IPv4 address (with port number).
1254 An 8 or 9 element vector represents an IPv6 address (with port number).
1255 If optional second argument OMIT-PORT is non-nil, don't include a port
1256 number in the string, even when present in ADDRESS.
1257 Returns nil if format of ADDRESS is invalid. */)
1258 (address, omit_port)
1259 Lisp_Object address, omit_port;
1260 {
1261 if (NILP (address))
1262 return Qnil;
1263
1264 if (STRINGP (address)) /* AF_LOCAL */
1265 return address;
1266
1267 if (VECTORP (address)) /* AF_INET or AF_INET6 */
1268 {
1269 register struct Lisp_Vector *p = XVECTOR (address);
1270 Lisp_Object args[10];
1271 int nargs, i;
1272
1273 if (p->size == 4 || (p->size == 5 && !NILP (omit_port)))
1274 {
1275 args[0] = build_string ("%d.%d.%d.%d");
1276 nargs = 4;
1277 }
1278 else if (p->size == 5)
1279 {
1280 args[0] = build_string ("%d.%d.%d.%d:%d");
1281 nargs = 5;
1282 }
1283 else if (p->size == 8 || (p->size == 9 && !NILP (omit_port)))
1284 {
1285 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
1286 nargs = 8;
1287 }
1288 else if (p->size == 9)
1289 {
1290 args[0] = build_string ("[%x:%x:%x:%x:%x:%x:%x:%x]:%d");
1291 nargs = 9;
1292 }
1293 else
1294 return Qnil;
1295
1296 for (i = 0; i < nargs; i++)
1297 {
1298 EMACS_INT element = XINT (p->contents[i]);
1299
1300 if (element < 0 || element > 65535)
1301 return Qnil;
1302
1303 if (nargs <= 5 /* IPv4 */
1304 && i < 4 /* host, not port */
1305 && element > 255)
1306 return Qnil;
1307
1308 args[i+1] = p->contents[i];
1309 }
1310
1311 return Fformat (nargs+1, args);
1312 }
1313
1314 if (CONSP (address))
1315 {
1316 Lisp_Object args[2];
1317 args[0] = build_string ("<Family %d>");
1318 args[1] = Fcar (address);
1319 return Fformat (2, args);
1320 }
1321
1322 return Qnil;
1323 }
1324 #endif
1325 \f
1326 static Lisp_Object
1327 list_processes_1 (query_only)
1328 Lisp_Object query_only;
1329 {
1330 register Lisp_Object tail, tem;
1331 Lisp_Object proc, minspace, tem1;
1332 register struct Lisp_Process *p;
1333 char tembuf[300];
1334 int w_proc, w_buffer, w_tty;
1335 int exited = 0;
1336 Lisp_Object i_status, i_buffer, i_tty, i_command;
1337
1338 w_proc = 4; /* Proc */
1339 w_buffer = 6; /* Buffer */
1340 w_tty = 0; /* Omit if no ttys */
1341
1342 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
1343 {
1344 int i;
1345
1346 proc = Fcdr (XCAR (tail));
1347 p = XPROCESS (proc);
1348 if (NILP (p->type))
1349 continue;
1350 if (!NILP (query_only) && p->kill_without_query)
1351 continue;
1352 if (STRINGP (p->name)
1353 && ( i = SCHARS (p->name), (i > w_proc)))
1354 w_proc = i;
1355 if (!NILP (p->buffer))
1356 {
1357 if (NILP (XBUFFER (p->buffer)->name))
1358 {
1359 if (w_buffer < 8)
1360 w_buffer = 8; /* (Killed) */
1361 }
1362 else if ((i = SCHARS (XBUFFER (p->buffer)->name), (i > w_buffer)))
1363 w_buffer = i;
1364 }
1365 if (STRINGP (p->tty_name)
1366 && (i = SCHARS (p->tty_name), (i > w_tty)))
1367 w_tty = i;
1368 }
1369
1370 XSETFASTINT (i_status, w_proc + 1);
1371 XSETFASTINT (i_buffer, XFASTINT (i_status) + 9);
1372 if (w_tty)
1373 {
1374 XSETFASTINT (i_tty, XFASTINT (i_buffer) + w_buffer + 1);
1375 XSETFASTINT (i_command, XFASTINT (i_tty) + w_tty + 1);
1376 }
1377 else
1378 {
1379 i_tty = Qnil;
1380 XSETFASTINT (i_command, XFASTINT (i_buffer) + w_buffer + 1);
1381 }
1382
1383 XSETFASTINT (minspace, 1);
1384
1385 set_buffer_internal (XBUFFER (Vstandard_output));
1386 current_buffer->undo_list = Qt;
1387
1388 current_buffer->truncate_lines = Qt;
1389
1390 write_string ("Proc", -1);
1391 Findent_to (i_status, minspace); write_string ("Status", -1);
1392 Findent_to (i_buffer, minspace); write_string ("Buffer", -1);
1393 if (!NILP (i_tty))
1394 {
1395 Findent_to (i_tty, minspace); write_string ("Tty", -1);
1396 }
1397 Findent_to (i_command, minspace); write_string ("Command", -1);
1398 write_string ("\n", -1);
1399
1400 write_string ("----", -1);
1401 Findent_to (i_status, minspace); write_string ("------", -1);
1402 Findent_to (i_buffer, minspace); write_string ("------", -1);
1403 if (!NILP (i_tty))
1404 {
1405 Findent_to (i_tty, minspace); write_string ("---", -1);
1406 }
1407 Findent_to (i_command, minspace); write_string ("-------", -1);
1408 write_string ("\n", -1);
1409
1410 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
1411 {
1412 Lisp_Object symbol;
1413
1414 proc = Fcdr (XCAR (tail));
1415 p = XPROCESS (proc);
1416 if (NILP (p->type))
1417 continue;
1418 if (!NILP (query_only) && p->kill_without_query)
1419 continue;
1420
1421 Finsert (1, &p->name);
1422 Findent_to (i_status, minspace);
1423
1424 if (p->raw_status_new)
1425 update_status (p);
1426 symbol = p->status;
1427 if (CONSP (p->status))
1428 symbol = XCAR (p->status);
1429
1430 if (EQ (symbol, Qsignal))
1431 {
1432 Lisp_Object tem;
1433 tem = Fcar (Fcdr (p->status));
1434 Fprinc (symbol, Qnil);
1435 }
1436 else if (NETCONN1_P (p) || SERIALCONN1_P (p))
1437 {
1438 if (EQ (symbol, Qexit))
1439 write_string ("closed", -1);
1440 else if (EQ (p->command, Qt))
1441 write_string ("stopped", -1);
1442 else if (EQ (symbol, Qrun))
1443 write_string ("open", -1);
1444 else
1445 Fprinc (symbol, Qnil);
1446 }
1447 else if (SERIALCONN1_P (p))
1448 {
1449 write_string ("running", -1);
1450 }
1451 else
1452 Fprinc (symbol, Qnil);
1453
1454 if (EQ (symbol, Qexit))
1455 {
1456 Lisp_Object tem;
1457 tem = Fcar (Fcdr (p->status));
1458 if (XFASTINT (tem))
1459 {
1460 sprintf (tembuf, " %d", (int) XFASTINT (tem));
1461 write_string (tembuf, -1);
1462 }
1463 }
1464
1465 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit) || EQ (symbol, Qclosed))
1466 exited++;
1467
1468 Findent_to (i_buffer, minspace);
1469 if (NILP (p->buffer))
1470 insert_string ("(none)");
1471 else if (NILP (XBUFFER (p->buffer)->name))
1472 insert_string ("(Killed)");
1473 else
1474 Finsert (1, &XBUFFER (p->buffer)->name);
1475
1476 if (!NILP (i_tty))
1477 {
1478 Findent_to (i_tty, minspace);
1479 if (STRINGP (p->tty_name))
1480 Finsert (1, &p->tty_name);
1481 }
1482
1483 Findent_to (i_command, minspace);
1484
1485 if (EQ (p->status, Qlisten))
1486 {
1487 Lisp_Object port = Fplist_get (p->childp, QCservice);
1488 if (INTEGERP (port))
1489 port = Fnumber_to_string (port);
1490 if (NILP (port))
1491 port = Fformat_network_address (Fplist_get (p->childp, QClocal), Qnil);
1492 sprintf (tembuf, "(network %s server on %s)\n",
1493 (DATAGRAM_CHAN_P (p->infd) ? "datagram" : "stream"),
1494 (STRINGP (port) ? (char *)SDATA (port) : "?"));
1495 insert_string (tembuf);
1496 }
1497 else if (NETCONN1_P (p))
1498 {
1499 /* For a local socket, there is no host name,
1500 so display service instead. */
1501 Lisp_Object host = Fplist_get (p->childp, QChost);
1502 if (!STRINGP (host))
1503 {
1504 host = Fplist_get (p->childp, QCservice);
1505 if (INTEGERP (host))
1506 host = Fnumber_to_string (host);
1507 }
1508 if (NILP (host))
1509 host = Fformat_network_address (Fplist_get (p->childp, QCremote), Qnil);
1510 sprintf (tembuf, "(network %s connection to %s)\n",
1511 (DATAGRAM_CHAN_P (p->infd) ? "datagram" : "stream"),
1512 (STRINGP (host) ? (char *)SDATA (host) : "?"));
1513 insert_string (tembuf);
1514 }
1515 else if (SERIALCONN1_P (p))
1516 {
1517 Lisp_Object port = Fplist_get (p->childp, QCport);
1518 Lisp_Object speed = Fplist_get (p->childp, QCspeed);
1519 insert_string ("(serial port ");
1520 if (STRINGP (port))
1521 insert_string (SDATA (port));
1522 else
1523 insert_string ("?");
1524 if (INTEGERP (speed))
1525 {
1526 sprintf (tembuf, " at %ld b/s", (long) XINT (speed));
1527 insert_string (tembuf);
1528 }
1529 insert_string (")\n");
1530 }
1531 else
1532 {
1533 tem = p->command;
1534 while (1)
1535 {
1536 tem1 = Fcar (tem);
1537 if (NILP (tem1))
1538 break;
1539 Finsert (1, &tem1);
1540 tem = Fcdr (tem);
1541 if (NILP (tem))
1542 break;
1543 insert_string (" ");
1544 }
1545 insert_string ("\n");
1546 }
1547 }
1548 if (exited)
1549 {
1550 status_notify (NULL);
1551 redisplay_preserve_echo_area (13);
1552 }
1553 return Qnil;
1554 }
1555
1556 DEFUN ("list-processes", Flist_processes, Slist_processes, 0, 1, "P",
1557 doc: /* Display a list of all processes.
1558 If optional argument QUERY-ONLY is non-nil, only processes with
1559 the query-on-exit flag set will be listed.
1560 Any process listed as exited or signaled is actually eliminated
1561 after the listing is made. */)
1562 (query_only)
1563 Lisp_Object query_only;
1564 {
1565 internal_with_output_to_temp_buffer ("*Process List*",
1566 list_processes_1, query_only);
1567 return Qnil;
1568 }
1569
1570 DEFUN ("process-list", Fprocess_list, Sprocess_list, 0, 0, 0,
1571 doc: /* Return a list of all processes. */)
1572 ()
1573 {
1574 return Fmapcar (Qcdr, Vprocess_alist);
1575 }
1576 \f
1577 /* Starting asynchronous inferior processes. */
1578
1579 static Lisp_Object start_process_unwind ();
1580
1581 DEFUN ("start-process", Fstart_process, Sstart_process, 3, MANY, 0,
1582 doc: /* Start a program in a subprocess. Return the process object for it.
1583 NAME is name for process. It is modified if necessary to make it unique.
1584 BUFFER is the buffer (or buffer name) to associate with the process.
1585
1586 Process output (both standard output and standard error streams) goes
1587 at end of BUFFER, unless you specify an output stream or filter
1588 function to handle the output. BUFFER may also be nil, meaning that
1589 this process is not associated with any buffer.
1590
1591 PROGRAM is the program file name. It is searched for in PATH. If
1592 nil, just associate a pty with the buffer. Remaining arguments are
1593 strings to give program as arguments.
1594
1595 If you want to separate standard output from standard error, invoke
1596 the command through a shell and redirect one of them using the shell
1597 syntax.
1598
1599 usage: (start-process NAME BUFFER PROGRAM &rest PROGRAM-ARGS) */)
1600 (nargs, args)
1601 int nargs;
1602 register Lisp_Object *args;
1603 {
1604 Lisp_Object buffer, name, program, proc, current_dir, tem;
1605 register unsigned char **new_argv;
1606 register int i;
1607 int count = SPECPDL_INDEX ();
1608
1609 buffer = args[1];
1610 if (!NILP (buffer))
1611 buffer = Fget_buffer_create (buffer);
1612
1613 /* Make sure that the child will be able to chdir to the current
1614 buffer's current directory, or its unhandled equivalent. We
1615 can't just have the child check for an error when it does the
1616 chdir, since it's in a vfork.
1617
1618 We have to GCPRO around this because Fexpand_file_name and
1619 Funhandled_file_name_directory might call a file name handling
1620 function. The argument list is protected by the caller, so all
1621 we really have to worry about is buffer. */
1622 {
1623 struct gcpro gcpro1, gcpro2;
1624
1625 current_dir = current_buffer->directory;
1626
1627 GCPRO2 (buffer, current_dir);
1628
1629 current_dir = Funhandled_file_name_directory (current_dir);
1630 if (NILP (current_dir))
1631 /* If the file name handler says that current_dir is unreachable, use
1632 a sensible default. */
1633 current_dir = build_string ("~/");
1634 current_dir = expand_and_dir_to_file (current_dir, Qnil);
1635 if (NILP (Ffile_accessible_directory_p (current_dir)))
1636 report_file_error ("Setting current directory",
1637 Fcons (current_buffer->directory, Qnil));
1638
1639 UNGCPRO;
1640 }
1641
1642 name = args[0];
1643 CHECK_STRING (name);
1644
1645 program = args[2];
1646
1647 if (!NILP (program))
1648 CHECK_STRING (program);
1649
1650 proc = make_process (name);
1651 /* If an error occurs and we can't start the process, we want to
1652 remove it from the process list. This means that each error
1653 check in create_process doesn't need to call remove_process
1654 itself; it's all taken care of here. */
1655 record_unwind_protect (start_process_unwind, proc);
1656
1657 XPROCESS (proc)->childp = Qt;
1658 XPROCESS (proc)->plist = Qnil;
1659 XPROCESS (proc)->type = Qreal;
1660 XPROCESS (proc)->buffer = buffer;
1661 XPROCESS (proc)->sentinel = Qnil;
1662 XPROCESS (proc)->filter = Qnil;
1663 XPROCESS (proc)->command = Flist (nargs - 2, args + 2);
1664
1665 #ifdef ADAPTIVE_READ_BUFFERING
1666 XPROCESS (proc)->adaptive_read_buffering
1667 = (NILP (Vprocess_adaptive_read_buffering) ? 0
1668 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
1669 #endif
1670
1671 /* Make the process marker point into the process buffer (if any). */
1672 if (BUFFERP (buffer))
1673 set_marker_both (XPROCESS (proc)->mark, buffer,
1674 BUF_ZV (XBUFFER (buffer)),
1675 BUF_ZV_BYTE (XBUFFER (buffer)));
1676
1677 {
1678 /* Decide coding systems for communicating with the process. Here
1679 we don't setup the structure coding_system nor pay attention to
1680 unibyte mode. They are done in create_process. */
1681
1682 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1683 Lisp_Object coding_systems = Qt;
1684 Lisp_Object val, *args2;
1685 struct gcpro gcpro1, gcpro2;
1686
1687 val = Vcoding_system_for_read;
1688 if (NILP (val))
1689 {
1690 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof *args2);
1691 args2[0] = Qstart_process;
1692 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1693 GCPRO2 (proc, current_dir);
1694 if (!NILP (program))
1695 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1696 UNGCPRO;
1697 if (CONSP (coding_systems))
1698 val = XCAR (coding_systems);
1699 else if (CONSP (Vdefault_process_coding_system))
1700 val = XCAR (Vdefault_process_coding_system);
1701 }
1702 XPROCESS (proc)->decode_coding_system = val;
1703
1704 val = Vcoding_system_for_write;
1705 if (NILP (val))
1706 {
1707 if (EQ (coding_systems, Qt))
1708 {
1709 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof args2);
1710 args2[0] = Qstart_process;
1711 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1712 GCPRO2 (proc, current_dir);
1713 if (!NILP (program))
1714 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1715 UNGCPRO;
1716 }
1717 if (CONSP (coding_systems))
1718 val = XCDR (coding_systems);
1719 else if (CONSP (Vdefault_process_coding_system))
1720 val = XCDR (Vdefault_process_coding_system);
1721 }
1722 XPROCESS (proc)->encode_coding_system = val;
1723 }
1724
1725
1726 XPROCESS (proc)->decoding_buf = make_uninit_string (0);
1727 XPROCESS (proc)->decoding_carryover = 0;
1728 XPROCESS (proc)->encoding_buf = make_uninit_string (0);
1729
1730 XPROCESS (proc)->inherit_coding_system_flag
1731 = !(NILP (buffer) || !inherit_process_coding_system);
1732
1733 if (!NILP (program))
1734 {
1735 /* If program file name is not absolute, search our path for it.
1736 Put the name we will really use in TEM. */
1737 if (!IS_DIRECTORY_SEP (SREF (program, 0))
1738 && !(SCHARS (program) > 1
1739 && IS_DEVICE_SEP (SREF (program, 1))))
1740 {
1741 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1742
1743 tem = Qnil;
1744 GCPRO4 (name, program, buffer, current_dir);
1745 openp (Vexec_path, program, Vexec_suffixes, &tem, make_number (X_OK));
1746 UNGCPRO;
1747 if (NILP (tem))
1748 report_file_error ("Searching for program", Fcons (program, Qnil));
1749 tem = Fexpand_file_name (tem, Qnil);
1750 }
1751 else
1752 {
1753 if (!NILP (Ffile_directory_p (program)))
1754 error ("Specified program for new process is a directory");
1755 tem = program;
1756 }
1757
1758 /* If program file name starts with /: for quoting a magic name,
1759 discard that. */
1760 if (SBYTES (tem) > 2 && SREF (tem, 0) == '/'
1761 && SREF (tem, 1) == ':')
1762 tem = Fsubstring (tem, make_number (2), Qnil);
1763
1764 {
1765 struct gcpro gcpro1;
1766 GCPRO1 (tem);
1767
1768 /* Encode the file name and put it in NEW_ARGV.
1769 That's where the child will use it to execute the program. */
1770 tem = Fcons (ENCODE_FILE (tem), Qnil);
1771
1772 /* Here we encode arguments by the coding system used for sending
1773 data to the process. We don't support using different coding
1774 systems for encoding arguments and for encoding data sent to the
1775 process. */
1776
1777 for (i = 3; i < nargs; i++)
1778 {
1779 tem = Fcons (args[i], tem);
1780 CHECK_STRING (XCAR (tem));
1781 if (STRING_MULTIBYTE (XCAR (tem)))
1782 XSETCAR (tem,
1783 code_convert_string_norecord
1784 (XCAR (tem), XPROCESS (proc)->encode_coding_system, 1));
1785 }
1786
1787 UNGCPRO;
1788 }
1789
1790 /* Now that everything is encoded we can collect the strings into
1791 NEW_ARGV. */
1792 new_argv = (unsigned char **) alloca ((nargs - 1) * sizeof (char *));
1793 new_argv[nargs - 2] = 0;
1794
1795 for (i = nargs - 3; i >= 0; i--)
1796 {
1797 new_argv[i] = SDATA (XCAR (tem));
1798 tem = XCDR (tem);
1799 }
1800
1801 create_process (proc, (char **) new_argv, current_dir);
1802 }
1803 else
1804 create_pty (proc);
1805
1806 return unbind_to (count, proc);
1807 }
1808
1809 /* This function is the unwind_protect form for Fstart_process. If
1810 PROC doesn't have its pid set, then we know someone has signaled
1811 an error and the process wasn't started successfully, so we should
1812 remove it from the process list. */
1813 static Lisp_Object
1814 start_process_unwind (proc)
1815 Lisp_Object proc;
1816 {
1817 if (!PROCESSP (proc))
1818 abort ();
1819
1820 /* Was PROC started successfully? */
1821 if (XPROCESS (proc)->pid == -1)
1822 remove_process (proc);
1823
1824 return Qnil;
1825 }
1826
1827 static void
1828 create_process_1 (timer)
1829 struct atimer *timer;
1830 {
1831 /* Nothing to do. */
1832 }
1833
1834
1835 #if 0 /* This doesn't work; see the note before sigchld_handler. */
1836 #ifdef USG
1837 #ifdef SIGCHLD
1838 /* Mimic blocking of signals on system V, which doesn't really have it. */
1839
1840 /* Nonzero means we got a SIGCHLD when it was supposed to be blocked. */
1841 int sigchld_deferred;
1842
1843 SIGTYPE
1844 create_process_sigchld ()
1845 {
1846 signal (SIGCHLD, create_process_sigchld);
1847
1848 sigchld_deferred = 1;
1849 }
1850 #endif
1851 #endif
1852 #endif
1853
1854 void
1855 create_process (process, new_argv, current_dir)
1856 Lisp_Object process;
1857 char **new_argv;
1858 Lisp_Object current_dir;
1859 {
1860 int inchannel, outchannel;
1861 pid_t pid;
1862 int sv[2];
1863 #if !defined (WINDOWSNT) && defined (FD_CLOEXEC)
1864 int wait_child_setup[2];
1865 #endif
1866 #ifdef POSIX_SIGNALS
1867 sigset_t procmask;
1868 sigset_t blocked;
1869 struct sigaction sigint_action;
1870 struct sigaction sigquit_action;
1871 #ifdef AIX
1872 struct sigaction sighup_action;
1873 #endif
1874 #else /* !POSIX_SIGNALS */
1875 #if 0
1876 #ifdef SIGCHLD
1877 SIGTYPE (*sigchld)();
1878 #endif
1879 #endif /* 0 */
1880 #endif /* !POSIX_SIGNALS */
1881 /* Use volatile to protect variables from being clobbered by longjmp. */
1882 volatile int forkin, forkout;
1883 volatile int pty_flag = 0;
1884 #ifndef USE_CRT_DLL
1885 extern char **environ;
1886 #endif
1887
1888 inchannel = outchannel = -1;
1889
1890 #ifdef HAVE_PTYS
1891 if (!NILP (Vprocess_connection_type))
1892 outchannel = inchannel = allocate_pty ();
1893
1894 if (inchannel >= 0)
1895 {
1896 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1897 /* On most USG systems it does not work to open the pty's tty here,
1898 then close it and reopen it in the child. */
1899 #ifdef O_NOCTTY
1900 /* Don't let this terminal become our controlling terminal
1901 (in case we don't have one). */
1902 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1903 #else
1904 forkout = forkin = emacs_open (pty_name, O_RDWR, 0);
1905 #endif
1906 if (forkin < 0)
1907 report_file_error ("Opening pty", Qnil);
1908 #else
1909 forkin = forkout = -1;
1910 #endif /* not USG, or USG_SUBTTY_WORKS */
1911 pty_flag = 1;
1912 }
1913 else
1914 #endif /* HAVE_PTYS */
1915 {
1916 int tem;
1917 tem = pipe (sv);
1918 if (tem < 0)
1919 report_file_error ("Creating pipe", Qnil);
1920 inchannel = sv[0];
1921 forkout = sv[1];
1922 tem = pipe (sv);
1923 if (tem < 0)
1924 {
1925 emacs_close (inchannel);
1926 emacs_close (forkout);
1927 report_file_error ("Creating pipe", Qnil);
1928 }
1929 outchannel = sv[1];
1930 forkin = sv[0];
1931 }
1932
1933 #if !defined (WINDOWSNT) && defined (FD_CLOEXEC)
1934 {
1935 int tem;
1936
1937 tem = pipe (wait_child_setup);
1938 if (tem < 0)
1939 report_file_error ("Creating pipe", Qnil);
1940 tem = fcntl (wait_child_setup[1], F_GETFD, 0);
1941 if (tem >= 0)
1942 tem = fcntl (wait_child_setup[1], F_SETFD, tem | FD_CLOEXEC);
1943 if (tem < 0)
1944 {
1945 emacs_close (wait_child_setup[0]);
1946 emacs_close (wait_child_setup[1]);
1947 report_file_error ("Setting file descriptor flags", Qnil);
1948 }
1949 }
1950 #endif
1951
1952 #if 0
1953 /* Replaced by close_process_descs */
1954 set_exclusive_use (inchannel);
1955 set_exclusive_use (outchannel);
1956 #endif
1957
1958 #ifdef O_NONBLOCK
1959 fcntl (inchannel, F_SETFL, O_NONBLOCK);
1960 fcntl (outchannel, F_SETFL, O_NONBLOCK);
1961 #else
1962 #ifdef O_NDELAY
1963 fcntl (inchannel, F_SETFL, O_NDELAY);
1964 fcntl (outchannel, F_SETFL, O_NDELAY);
1965 #endif
1966 #endif
1967
1968 /* Record this as an active process, with its channels.
1969 As a result, child_setup will close Emacs's side of the pipes. */
1970 chan_process[inchannel] = process;
1971 XPROCESS (process)->infd = inchannel;
1972 XPROCESS (process)->outfd = outchannel;
1973
1974 /* Previously we recorded the tty descriptor used in the subprocess.
1975 It was only used for getting the foreground tty process, so now
1976 we just reopen the device (see emacs_get_tty_pgrp) as this is
1977 more portable (see USG_SUBTTY_WORKS above). */
1978
1979 XPROCESS (process)->pty_flag = pty_flag;
1980 XPROCESS (process)->status = Qrun;
1981 setup_process_coding_systems (process);
1982
1983 /* Delay interrupts until we have a chance to store
1984 the new fork's pid in its process structure */
1985 #ifdef POSIX_SIGNALS
1986 sigemptyset (&blocked);
1987 #ifdef SIGCHLD
1988 sigaddset (&blocked, SIGCHLD);
1989 #endif
1990 #ifdef HAVE_WORKING_VFORK
1991 /* On many hosts (e.g. Solaris 2.4), if a vforked child calls `signal',
1992 this sets the parent's signal handlers as well as the child's.
1993 So delay all interrupts whose handlers the child might munge,
1994 and record the current handlers so they can be restored later. */
1995 sigaddset (&blocked, SIGINT ); sigaction (SIGINT , 0, &sigint_action );
1996 sigaddset (&blocked, SIGQUIT); sigaction (SIGQUIT, 0, &sigquit_action);
1997 #ifdef AIX
1998 sigaddset (&blocked, SIGHUP ); sigaction (SIGHUP , 0, &sighup_action );
1999 #endif
2000 #endif /* HAVE_WORKING_VFORK */
2001 sigprocmask (SIG_BLOCK, &blocked, &procmask);
2002 #else /* !POSIX_SIGNALS */
2003 #ifdef SIGCHLD
2004 #if defined (BSD_SYSTEM) || defined (HPUX)
2005 sigsetmask (sigmask (SIGCHLD));
2006 #else /* ordinary USG */
2007 #if 0
2008 sigchld_deferred = 0;
2009 sigchld = signal (SIGCHLD, create_process_sigchld);
2010 #endif
2011 #endif /* ordinary USG */
2012 #endif /* SIGCHLD */
2013 #endif /* !POSIX_SIGNALS */
2014
2015 FD_SET (inchannel, &input_wait_mask);
2016 FD_SET (inchannel, &non_keyboard_wait_mask);
2017 if (inchannel > max_process_desc)
2018 max_process_desc = inchannel;
2019
2020 /* Until we store the proper pid, enable sigchld_handler
2021 to recognize an unknown pid as standing for this process.
2022 It is very important not to let this `marker' value stay
2023 in the table after this function has returned; if it does
2024 it might cause call-process to hang and subsequent asynchronous
2025 processes to get their return values scrambled. */
2026 XPROCESS (process)->pid = -1;
2027
2028 BLOCK_INPUT;
2029
2030 {
2031 /* child_setup must clobber environ on systems with true vfork.
2032 Protect it from permanent change. */
2033 char **save_environ = environ;
2034
2035 current_dir = ENCODE_FILE (current_dir);
2036
2037 #ifndef WINDOWSNT
2038 pid = vfork ();
2039 if (pid == 0)
2040 #endif /* not WINDOWSNT */
2041 {
2042 int xforkin = forkin;
2043 int xforkout = forkout;
2044
2045 #if 0 /* This was probably a mistake--it duplicates code later on,
2046 but fails to handle all the cases. */
2047 /* Make sure SIGCHLD is not blocked in the child. */
2048 sigsetmask (SIGEMPTYMASK);
2049 #endif
2050
2051 /* Make the pty be the controlling terminal of the process. */
2052 #ifdef HAVE_PTYS
2053 /* First, disconnect its current controlling terminal. */
2054 #ifdef HAVE_SETSID
2055 /* We tried doing setsid only if pty_flag, but it caused
2056 process_set_signal to fail on SGI when using a pipe. */
2057 setsid ();
2058 /* Make the pty's terminal the controlling terminal. */
2059 if (pty_flag)
2060 {
2061 #ifdef TIOCSCTTY
2062 /* We ignore the return value
2063 because faith@cs.unc.edu says that is necessary on Linux. */
2064 ioctl (xforkin, TIOCSCTTY, 0);
2065 #endif
2066 }
2067 #else /* not HAVE_SETSID */
2068 #ifdef USG
2069 /* It's very important to call setpgrp here and no time
2070 afterwards. Otherwise, we lose our controlling tty which
2071 is set when we open the pty. */
2072 setpgrp ();
2073 #endif /* USG */
2074 #endif /* not HAVE_SETSID */
2075 #if defined (HAVE_TERMIOS) && defined (LDISC1)
2076 if (pty_flag && xforkin >= 0)
2077 {
2078 struct termios t;
2079 tcgetattr (xforkin, &t);
2080 t.c_lflag = LDISC1;
2081 if (tcsetattr (xforkin, TCSANOW, &t) < 0)
2082 emacs_write (1, "create_process/tcsetattr LDISC1 failed\n", 39);
2083 }
2084 #else
2085 #if defined (NTTYDISC) && defined (TIOCSETD)
2086 if (pty_flag && xforkin >= 0)
2087 {
2088 /* Use new line discipline. */
2089 int ldisc = NTTYDISC;
2090 ioctl (xforkin, TIOCSETD, &ldisc);
2091 }
2092 #endif
2093 #endif
2094 #ifdef TIOCNOTTY
2095 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
2096 can do TIOCSPGRP only to the process's controlling tty. */
2097 if (pty_flag)
2098 {
2099 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
2100 I can't test it since I don't have 4.3. */
2101 int j = emacs_open ("/dev/tty", O_RDWR, 0);
2102 ioctl (j, TIOCNOTTY, 0);
2103 emacs_close (j);
2104 #ifndef USG
2105 /* In order to get a controlling terminal on some versions
2106 of BSD, it is necessary to put the process in pgrp 0
2107 before it opens the terminal. */
2108 #ifdef HAVE_SETPGID
2109 setpgid (0, 0);
2110 #else
2111 setpgrp (0, 0);
2112 #endif
2113 #endif
2114 }
2115 #endif /* TIOCNOTTY */
2116
2117 #if !defined (DONT_REOPEN_PTY)
2118 /*** There is a suggestion that this ought to be a
2119 conditional on TIOCSPGRP,
2120 or !(defined (HAVE_SETSID) && defined (TIOCSCTTY)).
2121 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
2122 that system does seem to need this code, even though
2123 both HAVE_SETSID and TIOCSCTTY are defined. */
2124 /* Now close the pty (if we had it open) and reopen it.
2125 This makes the pty the controlling terminal of the subprocess. */
2126 if (pty_flag)
2127 {
2128
2129 /* I wonder if emacs_close (emacs_open (pty_name, ...))
2130 would work? */
2131 if (xforkin >= 0)
2132 emacs_close (xforkin);
2133 xforkout = xforkin = emacs_open (pty_name, O_RDWR, 0);
2134
2135 if (xforkin < 0)
2136 {
2137 emacs_write (1, "Couldn't open the pty terminal ", 31);
2138 emacs_write (1, pty_name, strlen (pty_name));
2139 emacs_write (1, "\n", 1);
2140 _exit (1);
2141 }
2142
2143 }
2144 #endif /* not DONT_REOPEN_PTY */
2145
2146 #ifdef SETUP_SLAVE_PTY
2147 if (pty_flag)
2148 {
2149 SETUP_SLAVE_PTY;
2150 }
2151 #endif /* SETUP_SLAVE_PTY */
2152 #ifdef AIX
2153 /* On AIX, we've disabled SIGHUP above once we start a child on a pty.
2154 Now reenable it in the child, so it will die when we want it to. */
2155 if (pty_flag)
2156 signal (SIGHUP, SIG_DFL);
2157 #endif
2158 #endif /* HAVE_PTYS */
2159
2160 signal (SIGINT, SIG_DFL);
2161 signal (SIGQUIT, SIG_DFL);
2162
2163 /* Stop blocking signals in the child. */
2164 #ifdef POSIX_SIGNALS
2165 sigprocmask (SIG_SETMASK, &procmask, 0);
2166 #else /* !POSIX_SIGNALS */
2167 #ifdef SIGCHLD
2168 #if defined (BSD_SYSTEM) || defined (HPUX)
2169 sigsetmask (SIGEMPTYMASK);
2170 #else /* ordinary USG */
2171 #if 0
2172 signal (SIGCHLD, sigchld);
2173 #endif
2174 #endif /* ordinary USG */
2175 #endif /* SIGCHLD */
2176 #endif /* !POSIX_SIGNALS */
2177
2178 if (pty_flag)
2179 child_setup_tty (xforkout);
2180 #ifdef WINDOWSNT
2181 pid = child_setup (xforkin, xforkout, xforkout,
2182 new_argv, 1, current_dir);
2183 #else /* not WINDOWSNT */
2184 #ifdef FD_CLOEXEC
2185 emacs_close (wait_child_setup[0]);
2186 #endif
2187 child_setup (xforkin, xforkout, xforkout,
2188 new_argv, 1, current_dir);
2189 #endif /* not WINDOWSNT */
2190 }
2191 environ = save_environ;
2192 }
2193
2194 UNBLOCK_INPUT;
2195
2196 /* This runs in the Emacs process. */
2197 if (pid < 0)
2198 {
2199 if (forkin >= 0)
2200 emacs_close (forkin);
2201 if (forkin != forkout && forkout >= 0)
2202 emacs_close (forkout);
2203 }
2204 else
2205 {
2206 /* vfork succeeded. */
2207 XPROCESS (process)->pid = pid;
2208
2209 #ifdef WINDOWSNT
2210 register_child (pid, inchannel);
2211 #endif /* WINDOWSNT */
2212
2213 /* If the subfork execv fails, and it exits,
2214 this close hangs. I don't know why.
2215 So have an interrupt jar it loose. */
2216 {
2217 struct atimer *timer;
2218 EMACS_TIME offset;
2219
2220 stop_polling ();
2221 EMACS_SET_SECS_USECS (offset, 1, 0);
2222 timer = start_atimer (ATIMER_RELATIVE, offset, create_process_1, 0);
2223
2224 if (forkin >= 0)
2225 emacs_close (forkin);
2226
2227 cancel_atimer (timer);
2228 start_polling ();
2229 }
2230
2231 if (forkin != forkout && forkout >= 0)
2232 emacs_close (forkout);
2233
2234 #ifdef HAVE_PTYS
2235 if (pty_flag)
2236 XPROCESS (process)->tty_name = build_string (pty_name);
2237 else
2238 #endif
2239 XPROCESS (process)->tty_name = Qnil;
2240
2241 #if !defined (WINDOWSNT) && defined (FD_CLOEXEC)
2242 /* Wait for child_setup to complete in case that vfork is
2243 actually defined as fork. The descriptor wait_child_setup[1]
2244 of a pipe is closed at the child side either by close-on-exec
2245 on successful execvp or the _exit call in child_setup. */
2246 {
2247 char dummy;
2248
2249 emacs_close (wait_child_setup[1]);
2250 emacs_read (wait_child_setup[0], &dummy, 1);
2251 emacs_close (wait_child_setup[0]);
2252 }
2253 #endif
2254 }
2255
2256 /* Restore the signal state whether vfork succeeded or not.
2257 (We will signal an error, below, if it failed.) */
2258 #ifdef POSIX_SIGNALS
2259 #ifdef HAVE_WORKING_VFORK
2260 /* Restore the parent's signal handlers. */
2261 sigaction (SIGINT, &sigint_action, 0);
2262 sigaction (SIGQUIT, &sigquit_action, 0);
2263 #ifdef AIX
2264 sigaction (SIGHUP, &sighup_action, 0);
2265 #endif
2266 #endif /* HAVE_WORKING_VFORK */
2267 /* Stop blocking signals in the parent. */
2268 sigprocmask (SIG_SETMASK, &procmask, 0);
2269 #else /* !POSIX_SIGNALS */
2270 #ifdef SIGCHLD
2271 #if defined (BSD_SYSTEM) || defined (HPUX)
2272 sigsetmask (SIGEMPTYMASK);
2273 #else /* ordinary USG */
2274 #if 0
2275 signal (SIGCHLD, sigchld);
2276 /* Now really handle any of these signals
2277 that came in during this function. */
2278 if (sigchld_deferred)
2279 kill (getpid (), SIGCHLD);
2280 #endif
2281 #endif /* ordinary USG */
2282 #endif /* SIGCHLD */
2283 #endif /* !POSIX_SIGNALS */
2284
2285 /* Now generate the error if vfork failed. */
2286 if (pid < 0)
2287 report_file_error ("Doing vfork", Qnil);
2288 }
2289
2290 void
2291 create_pty (process)
2292 Lisp_Object process;
2293 {
2294 int inchannel, outchannel;
2295
2296 /* Use volatile to protect variables from being clobbered by longjmp. */
2297 volatile int forkin, forkout;
2298 volatile int pty_flag = 0;
2299
2300 inchannel = outchannel = -1;
2301
2302 #ifdef HAVE_PTYS
2303 if (!NILP (Vprocess_connection_type))
2304 outchannel = inchannel = allocate_pty ();
2305
2306 if (inchannel >= 0)
2307 {
2308 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
2309 /* On most USG systems it does not work to open the pty's tty here,
2310 then close it and reopen it in the child. */
2311 #ifdef O_NOCTTY
2312 /* Don't let this terminal become our controlling terminal
2313 (in case we don't have one). */
2314 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
2315 #else
2316 forkout = forkin = emacs_open (pty_name, O_RDWR, 0);
2317 #endif
2318 if (forkin < 0)
2319 report_file_error ("Opening pty", Qnil);
2320 #if defined (RTU) || defined (UNIPLUS) || defined (DONT_REOPEN_PTY)
2321 /* In the case that vfork is defined as fork, the parent process
2322 (Emacs) may send some data before the child process completes
2323 tty options setup. So we setup tty before forking. */
2324 child_setup_tty (forkout);
2325 #endif /* RTU or UNIPLUS or DONT_REOPEN_PTY */
2326 #else
2327 forkin = forkout = -1;
2328 #endif /* not USG, or USG_SUBTTY_WORKS */
2329 pty_flag = 1;
2330 }
2331 #endif /* HAVE_PTYS */
2332
2333 #ifdef O_NONBLOCK
2334 fcntl (inchannel, F_SETFL, O_NONBLOCK);
2335 fcntl (outchannel, F_SETFL, O_NONBLOCK);
2336 #else
2337 #ifdef O_NDELAY
2338 fcntl (inchannel, F_SETFL, O_NDELAY);
2339 fcntl (outchannel, F_SETFL, O_NDELAY);
2340 #endif
2341 #endif
2342
2343 /* Record this as an active process, with its channels.
2344 As a result, child_setup will close Emacs's side of the pipes. */
2345 chan_process[inchannel] = process;
2346 XPROCESS (process)->infd = inchannel;
2347 XPROCESS (process)->outfd = outchannel;
2348
2349 /* Previously we recorded the tty descriptor used in the subprocess.
2350 It was only used for getting the foreground tty process, so now
2351 we just reopen the device (see emacs_get_tty_pgrp) as this is
2352 more portable (see USG_SUBTTY_WORKS above). */
2353
2354 XPROCESS (process)->pty_flag = pty_flag;
2355 XPROCESS (process)->status = Qrun;
2356 setup_process_coding_systems (process);
2357
2358 FD_SET (inchannel, &input_wait_mask);
2359 FD_SET (inchannel, &non_keyboard_wait_mask);
2360 if (inchannel > max_process_desc)
2361 max_process_desc = inchannel;
2362
2363 XPROCESS (process)->pid = -2;
2364 #ifdef HAVE_PTYS
2365 if (pty_flag)
2366 XPROCESS (process)->tty_name = build_string (pty_name);
2367 else
2368 #endif
2369 XPROCESS (process)->tty_name = Qnil;
2370 }
2371
2372 \f
2373 #ifdef HAVE_SOCKETS
2374
2375 /* Convert an internal struct sockaddr to a lisp object (vector or string).
2376 The address family of sa is not included in the result. */
2377
2378 static Lisp_Object
2379 conv_sockaddr_to_lisp (sa, len)
2380 struct sockaddr *sa;
2381 int len;
2382 {
2383 Lisp_Object address;
2384 int i;
2385 unsigned char *cp;
2386 register struct Lisp_Vector *p;
2387
2388 /* Workaround for a bug in getsockname on BSD: Names bound to
2389 sockets in the UNIX domain are inaccessible; getsockname returns
2390 a zero length name. */
2391 if (len < OFFSETOF (struct sockaddr, sa_family) + sizeof (sa->sa_family))
2392 return empty_unibyte_string;
2393
2394 switch (sa->sa_family)
2395 {
2396 case AF_INET:
2397 {
2398 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2399 len = sizeof (sin->sin_addr) + 1;
2400 address = Fmake_vector (make_number (len), Qnil);
2401 p = XVECTOR (address);
2402 p->contents[--len] = make_number (ntohs (sin->sin_port));
2403 cp = (unsigned char *) &sin->sin_addr;
2404 break;
2405 }
2406 #ifdef AF_INET6
2407 case AF_INET6:
2408 {
2409 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2410 uint16_t *ip6 = (uint16_t *) &sin6->sin6_addr;
2411 len = sizeof (sin6->sin6_addr)/2 + 1;
2412 address = Fmake_vector (make_number (len), Qnil);
2413 p = XVECTOR (address);
2414 p->contents[--len] = make_number (ntohs (sin6->sin6_port));
2415 for (i = 0; i < len; i++)
2416 p->contents[i] = make_number (ntohs (ip6[i]));
2417 return address;
2418 }
2419 #endif
2420 #ifdef HAVE_LOCAL_SOCKETS
2421 case AF_LOCAL:
2422 {
2423 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2424 for (i = 0; i < sizeof (sockun->sun_path); i++)
2425 if (sockun->sun_path[i] == 0)
2426 break;
2427 return make_unibyte_string (sockun->sun_path, i);
2428 }
2429 #endif
2430 default:
2431 len -= OFFSETOF (struct sockaddr, sa_family) + sizeof (sa->sa_family);
2432 address = Fcons (make_number (sa->sa_family),
2433 Fmake_vector (make_number (len), Qnil));
2434 p = XVECTOR (XCDR (address));
2435 cp = (unsigned char *) &sa->sa_family + sizeof (sa->sa_family);
2436 break;
2437 }
2438
2439 i = 0;
2440 while (i < len)
2441 p->contents[i++] = make_number (*cp++);
2442
2443 return address;
2444 }
2445
2446
2447 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2448
2449 static int
2450 get_lisp_to_sockaddr_size (address, familyp)
2451 Lisp_Object address;
2452 int *familyp;
2453 {
2454 register struct Lisp_Vector *p;
2455
2456 if (VECTORP (address))
2457 {
2458 p = XVECTOR (address);
2459 if (p->size == 5)
2460 {
2461 *familyp = AF_INET;
2462 return sizeof (struct sockaddr_in);
2463 }
2464 #ifdef AF_INET6
2465 else if (p->size == 9)
2466 {
2467 *familyp = AF_INET6;
2468 return sizeof (struct sockaddr_in6);
2469 }
2470 #endif
2471 }
2472 #ifdef HAVE_LOCAL_SOCKETS
2473 else if (STRINGP (address))
2474 {
2475 *familyp = AF_LOCAL;
2476 return sizeof (struct sockaddr_un);
2477 }
2478 #endif
2479 else if (CONSP (address) && INTEGERP (XCAR (address)) && VECTORP (XCDR (address)))
2480 {
2481 struct sockaddr *sa;
2482 *familyp = XINT (XCAR (address));
2483 p = XVECTOR (XCDR (address));
2484 return p->size + sizeof (sa->sa_family);
2485 }
2486 return 0;
2487 }
2488
2489 /* Convert an address object (vector or string) to an internal sockaddr.
2490
2491 The address format has been basically validated by
2492 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2493 it could have come from user data. So if FAMILY is not valid,
2494 we return after zeroing *SA. */
2495
2496 static void
2497 conv_lisp_to_sockaddr (family, address, sa, len)
2498 int family;
2499 Lisp_Object address;
2500 struct sockaddr *sa;
2501 int len;
2502 {
2503 register struct Lisp_Vector *p;
2504 register unsigned char *cp = NULL;
2505 register int i;
2506
2507 bzero (sa, len);
2508
2509 if (VECTORP (address))
2510 {
2511 p = XVECTOR (address);
2512 if (family == AF_INET)
2513 {
2514 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2515 len = sizeof (sin->sin_addr) + 1;
2516 i = XINT (p->contents[--len]);
2517 sin->sin_port = htons (i);
2518 cp = (unsigned char *)&sin->sin_addr;
2519 sa->sa_family = family;
2520 }
2521 #ifdef AF_INET6
2522 else if (family == AF_INET6)
2523 {
2524 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2525 uint16_t *ip6 = (uint16_t *)&sin6->sin6_addr;
2526 len = sizeof (sin6->sin6_addr) + 1;
2527 i = XINT (p->contents[--len]);
2528 sin6->sin6_port = htons (i);
2529 for (i = 0; i < len; i++)
2530 if (INTEGERP (p->contents[i]))
2531 {
2532 int j = XFASTINT (p->contents[i]) & 0xffff;
2533 ip6[i] = ntohs (j);
2534 }
2535 sa->sa_family = family;
2536 }
2537 #endif
2538 return;
2539 }
2540 else if (STRINGP (address))
2541 {
2542 #ifdef HAVE_LOCAL_SOCKETS
2543 if (family == AF_LOCAL)
2544 {
2545 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2546 cp = SDATA (address);
2547 for (i = 0; i < sizeof (sockun->sun_path) && *cp; i++)
2548 sockun->sun_path[i] = *cp++;
2549 sa->sa_family = family;
2550 }
2551 #endif
2552 return;
2553 }
2554 else
2555 {
2556 p = XVECTOR (XCDR (address));
2557 cp = (unsigned char *)sa + sizeof (sa->sa_family);
2558 }
2559
2560 for (i = 0; i < len; i++)
2561 if (INTEGERP (p->contents[i]))
2562 *cp++ = XFASTINT (p->contents[i]) & 0xff;
2563 }
2564
2565 #ifdef DATAGRAM_SOCKETS
2566 DEFUN ("process-datagram-address", Fprocess_datagram_address, Sprocess_datagram_address,
2567 1, 1, 0,
2568 doc: /* Get the current datagram address associated with PROCESS. */)
2569 (process)
2570 Lisp_Object process;
2571 {
2572 int channel;
2573
2574 CHECK_PROCESS (process);
2575
2576 if (!DATAGRAM_CONN_P (process))
2577 return Qnil;
2578
2579 channel = XPROCESS (process)->infd;
2580 return conv_sockaddr_to_lisp (datagram_address[channel].sa,
2581 datagram_address[channel].len);
2582 }
2583
2584 DEFUN ("set-process-datagram-address", Fset_process_datagram_address, Sset_process_datagram_address,
2585 2, 2, 0,
2586 doc: /* Set the datagram address for PROCESS to ADDRESS.
2587 Returns nil upon error setting address, ADDRESS otherwise. */)
2588 (process, address)
2589 Lisp_Object process, address;
2590 {
2591 int channel;
2592 int family, len;
2593
2594 CHECK_PROCESS (process);
2595
2596 if (!DATAGRAM_CONN_P (process))
2597 return Qnil;
2598
2599 channel = XPROCESS (process)->infd;
2600
2601 len = get_lisp_to_sockaddr_size (address, &family);
2602 if (datagram_address[channel].len != len)
2603 return Qnil;
2604 conv_lisp_to_sockaddr (family, address, datagram_address[channel].sa, len);
2605 return address;
2606 }
2607 #endif
2608 \f
2609
2610 static struct socket_options {
2611 /* The name of this option. Should be lowercase version of option
2612 name without SO_ prefix. */
2613 char *name;
2614 /* Option level SOL_... */
2615 int optlevel;
2616 /* Option number SO_... */
2617 int optnum;
2618 enum { SOPT_UNKNOWN, SOPT_BOOL, SOPT_INT, SOPT_IFNAME, SOPT_LINGER } opttype;
2619 enum { OPIX_NONE=0, OPIX_MISC=1, OPIX_REUSEADDR=2 } optbit;
2620 } socket_options[] =
2621 {
2622 #ifdef SO_BINDTODEVICE
2623 { ":bindtodevice", SOL_SOCKET, SO_BINDTODEVICE, SOPT_IFNAME, OPIX_MISC },
2624 #endif
2625 #ifdef SO_BROADCAST
2626 { ":broadcast", SOL_SOCKET, SO_BROADCAST, SOPT_BOOL, OPIX_MISC },
2627 #endif
2628 #ifdef SO_DONTROUTE
2629 { ":dontroute", SOL_SOCKET, SO_DONTROUTE, SOPT_BOOL, OPIX_MISC },
2630 #endif
2631 #ifdef SO_KEEPALIVE
2632 { ":keepalive", SOL_SOCKET, SO_KEEPALIVE, SOPT_BOOL, OPIX_MISC },
2633 #endif
2634 #ifdef SO_LINGER
2635 { ":linger", SOL_SOCKET, SO_LINGER, SOPT_LINGER, OPIX_MISC },
2636 #endif
2637 #ifdef SO_OOBINLINE
2638 { ":oobinline", SOL_SOCKET, SO_OOBINLINE, SOPT_BOOL, OPIX_MISC },
2639 #endif
2640 #ifdef SO_PRIORITY
2641 { ":priority", SOL_SOCKET, SO_PRIORITY, SOPT_INT, OPIX_MISC },
2642 #endif
2643 #ifdef SO_REUSEADDR
2644 { ":reuseaddr", SOL_SOCKET, SO_REUSEADDR, SOPT_BOOL, OPIX_REUSEADDR },
2645 #endif
2646 { 0, 0, 0, SOPT_UNKNOWN, OPIX_NONE }
2647 };
2648
2649 /* Set option OPT to value VAL on socket S.
2650
2651 Returns (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2652 Signals an error if setting a known option fails.
2653 */
2654
2655 static int
2656 set_socket_option (s, opt, val)
2657 int s;
2658 Lisp_Object opt, val;
2659 {
2660 char *name;
2661 struct socket_options *sopt;
2662 int ret = 0;
2663
2664 CHECK_SYMBOL (opt);
2665
2666 name = (char *) SDATA (SYMBOL_NAME (opt));
2667 for (sopt = socket_options; sopt->name; sopt++)
2668 if (strcmp (name, sopt->name) == 0)
2669 break;
2670
2671 switch (sopt->opttype)
2672 {
2673 case SOPT_BOOL:
2674 {
2675 int optval;
2676 optval = NILP (val) ? 0 : 1;
2677 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2678 &optval, sizeof (optval));
2679 break;
2680 }
2681
2682 case SOPT_INT:
2683 {
2684 int optval;
2685 if (INTEGERP (val))
2686 optval = XINT (val);
2687 else
2688 error ("Bad option value for %s", name);
2689 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2690 &optval, sizeof (optval));
2691 break;
2692 }
2693
2694 #ifdef SO_BINDTODEVICE
2695 case SOPT_IFNAME:
2696 {
2697 char devname[IFNAMSIZ+1];
2698
2699 /* This is broken, at least in the Linux 2.4 kernel.
2700 To unbind, the arg must be a zero integer, not the empty string.
2701 This should work on all systems. KFS. 2003-09-23. */
2702 bzero (devname, sizeof devname);
2703 if (STRINGP (val))
2704 {
2705 char *arg = (char *) SDATA (val);
2706 int len = min (strlen (arg), IFNAMSIZ);
2707 bcopy (arg, devname, len);
2708 }
2709 else if (!NILP (val))
2710 error ("Bad option value for %s", name);
2711 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2712 devname, IFNAMSIZ);
2713 break;
2714 }
2715 #endif
2716
2717 #ifdef SO_LINGER
2718 case SOPT_LINGER:
2719 {
2720 struct linger linger;
2721
2722 linger.l_onoff = 1;
2723 linger.l_linger = 0;
2724 if (INTEGERP (val))
2725 linger.l_linger = XINT (val);
2726 else
2727 linger.l_onoff = NILP (val) ? 0 : 1;
2728 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2729 &linger, sizeof (linger));
2730 break;
2731 }
2732 #endif
2733
2734 default:
2735 return 0;
2736 }
2737
2738 if (ret < 0)
2739 report_file_error ("Cannot set network option",
2740 Fcons (opt, Fcons (val, Qnil)));
2741 return (1 << sopt->optbit);
2742 }
2743
2744
2745 DEFUN ("set-network-process-option",
2746 Fset_network_process_option, Sset_network_process_option,
2747 3, 4, 0,
2748 doc: /* For network process PROCESS set option OPTION to value VALUE.
2749 See `make-network-process' for a list of options and values.
2750 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2751 OPTION is not a supported option, return nil instead; otherwise return t. */)
2752 (process, option, value, no_error)
2753 Lisp_Object process, option, value;
2754 Lisp_Object no_error;
2755 {
2756 int s;
2757 struct Lisp_Process *p;
2758
2759 CHECK_PROCESS (process);
2760 p = XPROCESS (process);
2761 if (!NETCONN1_P (p))
2762 error ("Process is not a network process");
2763
2764 s = p->infd;
2765 if (s < 0)
2766 error ("Process is not running");
2767
2768 if (set_socket_option (s, option, value))
2769 {
2770 p->childp = Fplist_put (p->childp, option, value);
2771 return Qt;
2772 }
2773
2774 if (NILP (no_error))
2775 error ("Unknown or unsupported option");
2776
2777 return Qnil;
2778 }
2779
2780 \f
2781 #ifdef HAVE_SERIAL
2782 DEFUN ("serial-process-configure",
2783 Fserial_process_configure,
2784 Sserial_process_configure,
2785 0, MANY, 0,
2786 doc: /* Configure speed, bytesize, etc. of a serial process.
2787
2788 Arguments are specified as keyword/argument pairs. Attributes that
2789 are not given are re-initialized from the process's current
2790 configuration (available via the function `process-contact') or set to
2791 reasonable default values. The following arguments are defined:
2792
2793 :process PROCESS
2794 :name NAME
2795 :buffer BUFFER
2796 :port PORT
2797 -- Any of these arguments can be given to identify the process that is
2798 to be configured. If none of these arguments is given, the current
2799 buffer's process is used.
2800
2801 :speed SPEED -- SPEED is the speed of the serial port in bits per
2802 second, also called baud rate. Any value can be given for SPEED, but
2803 most serial ports work only at a few defined values between 1200 and
2804 115200, with 9600 being the most common value. If SPEED is nil, the
2805 serial port is not configured any further, i.e., all other arguments
2806 are ignored. This may be useful for special serial ports such as
2807 Bluetooth-to-serial converters which can only be configured through AT
2808 commands. A value of nil for SPEED can be used only when passed
2809 through `make-serial-process' or `serial-term'.
2810
2811 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2812 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2813
2814 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2815 `odd' (use odd parity), or the symbol `even' (use even parity). If
2816 PARITY is not given, no parity is used.
2817
2818 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2819 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2820 is not given or nil, 1 stopbit is used.
2821
2822 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2823 flowcontrol to be used, which is either nil (don't use flowcontrol),
2824 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2825 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2826 flowcontrol is used.
2827
2828 `serial-process-configure' is called by `make-serial-process' for the
2829 initial configuration of the serial port.
2830
2831 Examples:
2832
2833 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2834
2835 \(serial-process-configure
2836 :buffer "COM1" :stopbits 1 :parity 'odd :flowcontrol 'hw)
2837
2838 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2839
2840 usage: (serial-process-configure &rest ARGS) */)
2841 (nargs, args)
2842 int nargs;
2843 Lisp_Object *args;
2844 {
2845 struct Lisp_Process *p;
2846 Lisp_Object contact = Qnil;
2847 Lisp_Object proc = Qnil;
2848 struct gcpro gcpro1;
2849
2850 contact = Flist (nargs, args);
2851 GCPRO1 (contact);
2852
2853 proc = Fplist_get (contact, QCprocess);
2854 if (NILP (proc))
2855 proc = Fplist_get (contact, QCname);
2856 if (NILP (proc))
2857 proc = Fplist_get (contact, QCbuffer);
2858 if (NILP (proc))
2859 proc = Fplist_get (contact, QCport);
2860 proc = get_process (proc);
2861 p = XPROCESS (proc);
2862 if (!EQ (p->type, Qserial))
2863 error ("Not a serial process");
2864
2865 if (NILP (Fplist_get (p->childp, QCspeed)))
2866 {
2867 UNGCPRO;
2868 return Qnil;
2869 }
2870
2871 serial_configure (p, contact);
2872
2873 UNGCPRO;
2874 return Qnil;
2875 }
2876
2877 /* Used by make-serial-process to recover from errors. */
2878 Lisp_Object make_serial_process_unwind (Lisp_Object proc)
2879 {
2880 if (!PROCESSP (proc))
2881 abort ();
2882 remove_process (proc);
2883 return Qnil;
2884 }
2885
2886 DEFUN ("make-serial-process", Fmake_serial_process, Smake_serial_process,
2887 0, MANY, 0,
2888 doc: /* Create and return a serial port process.
2889
2890 In Emacs, serial port connections are represented by process objects,
2891 so input and output work as for subprocesses, and `delete-process'
2892 closes a serial port connection. However, a serial process has no
2893 process id, it cannot be signaled, and the status codes are different
2894 from normal processes.
2895
2896 `make-serial-process' creates a process and a buffer, on which you
2897 probably want to use `process-send-string'. Try \\[serial-term] for
2898 an interactive terminal. See below for examples.
2899
2900 Arguments are specified as keyword/argument pairs. The following
2901 arguments are defined:
2902
2903 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2904 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2905 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2906 the backslashes in strings).
2907
2908 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2909 which is called by `make-serial-process'.
2910
2911 :name NAME -- NAME is the name of the process. If NAME is not given,
2912 the value of PORT is used.
2913
2914 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2915 with the process. Process output goes at the end of that buffer,
2916 unless you specify an output stream or filter function to handle the
2917 output. If BUFFER is not given, the value of NAME is used.
2918
2919 :coding CODING -- If CODING is a symbol, it specifies the coding
2920 system used for both reading and writing for this process. If CODING
2921 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2922 ENCODING is used for writing.
2923
2924 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2925 the process is running. If BOOL is not given, query before exiting.
2926
2927 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2928 In the stopped state, a serial process does not accept incoming data,
2929 but you can send outgoing data. The stopped state is cleared by
2930 `continue-process' and set by `stop-process'.
2931
2932 :filter FILTER -- Install FILTER as the process filter.
2933
2934 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2935
2936 :plist PLIST -- Install PLIST as the initial plist of the process.
2937
2938 :speed
2939 :bytesize
2940 :parity
2941 :stopbits
2942 :flowcontrol
2943 -- These arguments are handled by `serial-process-configure', which is
2944 called by `make-serial-process'.
2945
2946 The original argument list, possibly modified by later configuration,
2947 is available via the function `process-contact'.
2948
2949 Examples:
2950
2951 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
2952
2953 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2954
2955 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity 'odd)
2956
2957 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2958
2959 usage: (make-serial-process &rest ARGS) */)
2960 (nargs, args)
2961 int nargs;
2962 Lisp_Object *args;
2963 {
2964 int fd = -1;
2965 Lisp_Object proc, contact, port;
2966 struct Lisp_Process *p;
2967 struct gcpro gcpro1;
2968 Lisp_Object name, buffer;
2969 Lisp_Object tem, val;
2970 int specpdl_count = -1;
2971
2972 if (nargs == 0)
2973 return Qnil;
2974
2975 contact = Flist (nargs, args);
2976 GCPRO1 (contact);
2977
2978 port = Fplist_get (contact, QCport);
2979 if (NILP (port))
2980 error ("No port specified");
2981 CHECK_STRING (port);
2982
2983 if (NILP (Fplist_member (contact, QCspeed)))
2984 error (":speed not specified");
2985 if (!NILP (Fplist_get (contact, QCspeed)))
2986 CHECK_NUMBER (Fplist_get (contact, QCspeed));
2987
2988 name = Fplist_get (contact, QCname);
2989 if (NILP (name))
2990 name = port;
2991 CHECK_STRING (name);
2992 proc = make_process (name);
2993 specpdl_count = SPECPDL_INDEX ();
2994 record_unwind_protect (make_serial_process_unwind, proc);
2995 p = XPROCESS (proc);
2996
2997 fd = serial_open ((char*) SDATA (port));
2998 p->infd = fd;
2999 p->outfd = fd;
3000 if (fd > max_process_desc)
3001 max_process_desc = fd;
3002 chan_process[fd] = proc;
3003
3004 buffer = Fplist_get (contact, QCbuffer);
3005 if (NILP (buffer))
3006 buffer = name;
3007 buffer = Fget_buffer_create (buffer);
3008 p->buffer = buffer;
3009
3010 p->childp = contact;
3011 p->plist = Fcopy_sequence (Fplist_get (contact, QCplist));
3012 p->type = Qserial;
3013 p->sentinel = Fplist_get (contact, QCsentinel);
3014 p->filter = Fplist_get (contact, QCfilter);
3015 p->log = Qnil;
3016 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
3017 p->kill_without_query = 1;
3018 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
3019 p->command = Qt;
3020 p->pty_flag = 0;
3021
3022 if (!EQ (p->command, Qt))
3023 {
3024 FD_SET (fd, &input_wait_mask);
3025 FD_SET (fd, &non_keyboard_wait_mask);
3026 }
3027
3028 if (BUFFERP (buffer))
3029 {
3030 set_marker_both (p->mark, buffer,
3031 BUF_ZV (XBUFFER (buffer)),
3032 BUF_ZV_BYTE (XBUFFER (buffer)));
3033 }
3034
3035 tem = Fplist_member (contact, QCcoding);
3036 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
3037 tem = Qnil;
3038
3039 val = Qnil;
3040 if (!NILP (tem))
3041 {
3042 val = XCAR (XCDR (tem));
3043 if (CONSP (val))
3044 val = XCAR (val);
3045 }
3046 else if (!NILP (Vcoding_system_for_read))
3047 val = Vcoding_system_for_read;
3048 else if ((!NILP (buffer) && NILP (XBUFFER (buffer)->enable_multibyte_characters))
3049 || (NILP (buffer) && NILP (buffer_defaults.enable_multibyte_characters)))
3050 val = Qnil;
3051 p->decode_coding_system = val;
3052
3053 val = Qnil;
3054 if (!NILP (tem))
3055 {
3056 val = XCAR (XCDR (tem));
3057 if (CONSP (val))
3058 val = XCDR (val);
3059 }
3060 else if (!NILP (Vcoding_system_for_write))
3061 val = Vcoding_system_for_write;
3062 else if ((!NILP (buffer) && NILP (XBUFFER (buffer)->enable_multibyte_characters))
3063 || (NILP (buffer) && NILP (buffer_defaults.enable_multibyte_characters)))
3064 val = Qnil;
3065 p->encode_coding_system = val;
3066
3067 setup_process_coding_systems (proc);
3068 p->decoding_buf = make_uninit_string (0);
3069 p->decoding_carryover = 0;
3070 p->encoding_buf = make_uninit_string (0);
3071 p->inherit_coding_system_flag
3072 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
3073
3074 Fserial_process_configure(nargs, args);
3075
3076 specpdl_ptr = specpdl + specpdl_count;
3077
3078 UNGCPRO;
3079 return proc;
3080 }
3081 #endif /* HAVE_SERIAL */
3082
3083 /* Create a network stream/datagram client/server process. Treated
3084 exactly like a normal process when reading and writing. Primary
3085 differences are in status display and process deletion. A network
3086 connection has no PID; you cannot signal it. All you can do is
3087 stop/continue it and deactivate/close it via delete-process */
3088
3089 DEFUN ("make-network-process", Fmake_network_process, Smake_network_process,
3090 0, MANY, 0,
3091 doc: /* Create and return a network server or client process.
3092
3093 In Emacs, network connections are represented by process objects, so
3094 input and output work as for subprocesses and `delete-process' closes
3095 a network connection. However, a network process has no process id,
3096 it cannot be signaled, and the status codes are different from normal
3097 processes.
3098
3099 Arguments are specified as keyword/argument pairs. The following
3100 arguments are defined:
3101
3102 :name NAME -- NAME is name for process. It is modified if necessary
3103 to make it unique.
3104
3105 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
3106 with the process. Process output goes at end of that buffer, unless
3107 you specify an output stream or filter function to handle the output.
3108 BUFFER may be also nil, meaning that this process is not associated
3109 with any buffer.
3110
3111 :host HOST -- HOST is name of the host to connect to, or its IP
3112 address. The symbol `local' specifies the local host. If specified
3113 for a server process, it must be a valid name or address for the local
3114 host, and only clients connecting to that address will be accepted.
3115
3116 :service SERVICE -- SERVICE is name of the service desired, or an
3117 integer specifying a port number to connect to. If SERVICE is t,
3118 a random port number is selected for the server. (If Emacs was
3119 compiled with getaddrinfo, a port number can also be specified as a
3120 string, e.g. "80", as well as an integer. This is not portable.)
3121
3122 :type TYPE -- TYPE is the type of connection. The default (nil) is a
3123 stream type connection, `datagram' creates a datagram type connection.
3124
3125 :family FAMILY -- FAMILY is the address (and protocol) family for the
3126 service specified by HOST and SERVICE. The default (nil) is to use
3127 whatever address family (IPv4 or IPv6) that is defined for the host
3128 and port number specified by HOST and SERVICE. Other address families
3129 supported are:
3130 local -- for a local (i.e. UNIX) address specified by SERVICE.
3131 ipv4 -- use IPv4 address family only.
3132 ipv6 -- use IPv6 address family only.
3133
3134 :local ADDRESS -- ADDRESS is the local address used for the connection.
3135 This parameter is ignored when opening a client process. When specified
3136 for a server process, the FAMILY, HOST and SERVICE args are ignored.
3137
3138 :remote ADDRESS -- ADDRESS is the remote partner's address for the
3139 connection. This parameter is ignored when opening a stream server
3140 process. For a datagram server process, it specifies the initial
3141 setting of the remote datagram address. When specified for a client
3142 process, the FAMILY, HOST, and SERVICE args are ignored.
3143
3144 The format of ADDRESS depends on the address family:
3145 - An IPv4 address is represented as an vector of integers [A B C D P]
3146 corresponding to numeric IP address A.B.C.D and port number P.
3147 - A local address is represented as a string with the address in the
3148 local address space.
3149 - An "unsupported family" address is represented by a cons (F . AV)
3150 where F is the family number and AV is a vector containing the socket
3151 address data with one element per address data byte. Do not rely on
3152 this format in portable code, as it may depend on implementation
3153 defined constants, data sizes, and data structure alignment.
3154
3155 :coding CODING -- If CODING is a symbol, it specifies the coding
3156 system used for both reading and writing for this process. If CODING
3157 is a cons (DECODING . ENCODING), DECODING is used for reading, and
3158 ENCODING is used for writing.
3159
3160 :nowait BOOL -- If BOOL is non-nil for a stream type client process,
3161 return without waiting for the connection to complete; instead, the
3162 sentinel function will be called with second arg matching "open" (if
3163 successful) or "failed" when the connect completes. Default is to use
3164 a blocking connect (i.e. wait) for stream type connections.
3165
3166 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
3167 running when Emacs is exited.
3168
3169 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
3170 In the stopped state, a server process does not accept new
3171 connections, and a client process does not handle incoming traffic.
3172 The stopped state is cleared by `continue-process' and set by
3173 `stop-process'.
3174
3175 :filter FILTER -- Install FILTER as the process filter.
3176
3177 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
3178 process filter are multibyte, otherwise they are unibyte.
3179 If this keyword is not specified, the strings are multibyte if
3180 `default-enable-multibyte-characters' is non-nil.
3181
3182 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
3183
3184 :log LOG -- Install LOG as the server process log function. This
3185 function is called when the server accepts a network connection from a
3186 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
3187 is the server process, CLIENT is the new process for the connection,
3188 and MESSAGE is a string.
3189
3190 :plist PLIST -- Install PLIST as the new process' initial plist.
3191
3192 :server QLEN -- if QLEN is non-nil, create a server process for the
3193 specified FAMILY, SERVICE, and connection type (stream or datagram).
3194 If QLEN is an integer, it is used as the max. length of the server's
3195 pending connection queue (also known as the backlog); the default
3196 queue length is 5. Default is to create a client process.
3197
3198 The following network options can be specified for this connection:
3199
3200 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
3201 :dontroute BOOL -- Only send to directly connected hosts.
3202 :keepalive BOOL -- Send keep-alive messages on network stream.
3203 :linger BOOL or TIMEOUT -- Send queued messages before closing.
3204 :oobinline BOOL -- Place out-of-band data in receive data stream.
3205 :priority INT -- Set protocol defined priority for sent packets.
3206 :reuseaddr BOOL -- Allow reusing a recently used local address
3207 (this is allowed by default for a server process).
3208 :bindtodevice NAME -- bind to interface NAME. Using this may require
3209 special privileges on some systems.
3210
3211 Consult the relevant system programmer's manual pages for more
3212 information on using these options.
3213
3214
3215 A server process will listen for and accept connections from clients.
3216 When a client connection is accepted, a new network process is created
3217 for the connection with the following parameters:
3218
3219 - The client's process name is constructed by concatenating the server
3220 process' NAME and a client identification string.
3221 - If the FILTER argument is non-nil, the client process will not get a
3222 separate process buffer; otherwise, the client's process buffer is a newly
3223 created buffer named after the server process' BUFFER name or process
3224 NAME concatenated with the client identification string.
3225 - The connection type and the process filter and sentinel parameters are
3226 inherited from the server process' TYPE, FILTER and SENTINEL.
3227 - The client process' contact info is set according to the client's
3228 addressing information (typically an IP address and a port number).
3229 - The client process' plist is initialized from the server's plist.
3230
3231 Notice that the FILTER and SENTINEL args are never used directly by
3232 the server process. Also, the BUFFER argument is not used directly by
3233 the server process, but via the optional :log function, accepted (and
3234 failed) connections may be logged in the server process' buffer.
3235
3236 The original argument list, modified with the actual connection
3237 information, is available via the `process-contact' function.
3238
3239 usage: (make-network-process &rest ARGS) */)
3240 (nargs, args)
3241 int nargs;
3242 Lisp_Object *args;
3243 {
3244 Lisp_Object proc;
3245 Lisp_Object contact;
3246 struct Lisp_Process *p;
3247 #ifdef HAVE_GETADDRINFO
3248 struct addrinfo ai, *res, *lres;
3249 struct addrinfo hints;
3250 char *portstring, portbuf[128];
3251 #else /* HAVE_GETADDRINFO */
3252 struct _emacs_addrinfo
3253 {
3254 int ai_family;
3255 int ai_socktype;
3256 int ai_protocol;
3257 int ai_addrlen;
3258 struct sockaddr *ai_addr;
3259 struct _emacs_addrinfo *ai_next;
3260 } ai, *res, *lres;
3261 #endif /* HAVE_GETADDRINFO */
3262 struct sockaddr_in address_in;
3263 #ifdef HAVE_LOCAL_SOCKETS
3264 struct sockaddr_un address_un;
3265 #endif
3266 int port;
3267 int ret = 0;
3268 int xerrno = 0;
3269 int s = -1, outch, inch;
3270 struct gcpro gcpro1;
3271 int count = SPECPDL_INDEX ();
3272 int count1;
3273 Lisp_Object QCaddress; /* one of QClocal or QCremote */
3274 Lisp_Object tem;
3275 Lisp_Object name, buffer, host, service, address;
3276 Lisp_Object filter, sentinel;
3277 int is_non_blocking_client = 0;
3278 int is_server = 0, backlog = 5;
3279 int socktype;
3280 int family = -1;
3281
3282 if (nargs == 0)
3283 return Qnil;
3284
3285 /* Save arguments for process-contact and clone-process. */
3286 contact = Flist (nargs, args);
3287 GCPRO1 (contact);
3288
3289 #ifdef WINDOWSNT
3290 /* Ensure socket support is loaded if available. */
3291 init_winsock (TRUE);
3292 #endif
3293
3294 /* :type TYPE (nil: stream, datagram */
3295 tem = Fplist_get (contact, QCtype);
3296 if (NILP (tem))
3297 socktype = SOCK_STREAM;
3298 #ifdef DATAGRAM_SOCKETS
3299 else if (EQ (tem, Qdatagram))
3300 socktype = SOCK_DGRAM;
3301 #endif
3302 else
3303 error ("Unsupported connection type");
3304
3305 /* :server BOOL */
3306 tem = Fplist_get (contact, QCserver);
3307 if (!NILP (tem))
3308 {
3309 /* Don't support network sockets when non-blocking mode is
3310 not available, since a blocked Emacs is not useful. */
3311 #if !defined(O_NONBLOCK) && !defined(O_NDELAY)
3312 error ("Network servers not supported");
3313 #else
3314 is_server = 1;
3315 if (INTEGERP (tem))
3316 backlog = XINT (tem);
3317 #endif
3318 }
3319
3320 /* Make QCaddress an alias for :local (server) or :remote (client). */
3321 QCaddress = is_server ? QClocal : QCremote;
3322
3323 /* :nowait BOOL */
3324 if (!is_server && socktype == SOCK_STREAM
3325 && (tem = Fplist_get (contact, QCnowait), !NILP (tem)))
3326 {
3327 #ifndef NON_BLOCKING_CONNECT
3328 error ("Non-blocking connect not supported");
3329 #else
3330 is_non_blocking_client = 1;
3331 #endif
3332 }
3333
3334 name = Fplist_get (contact, QCname);
3335 buffer = Fplist_get (contact, QCbuffer);
3336 filter = Fplist_get (contact, QCfilter);
3337 sentinel = Fplist_get (contact, QCsentinel);
3338
3339 CHECK_STRING (name);
3340
3341 /* Initialize addrinfo structure in case we don't use getaddrinfo. */
3342 ai.ai_socktype = socktype;
3343 ai.ai_protocol = 0;
3344 ai.ai_next = NULL;
3345 res = &ai;
3346
3347 /* :local ADDRESS or :remote ADDRESS */
3348 address = Fplist_get (contact, QCaddress);
3349 if (!NILP (address))
3350 {
3351 host = service = Qnil;
3352
3353 if (!(ai.ai_addrlen = get_lisp_to_sockaddr_size (address, &family)))
3354 error ("Malformed :address");
3355 ai.ai_family = family;
3356 ai.ai_addr = alloca (ai.ai_addrlen);
3357 conv_lisp_to_sockaddr (family, address, ai.ai_addr, ai.ai_addrlen);
3358 goto open_socket;
3359 }
3360
3361 /* :family FAMILY -- nil (for Inet), local, or integer. */
3362 tem = Fplist_get (contact, QCfamily);
3363 if (NILP (tem))
3364 {
3365 #if defined(HAVE_GETADDRINFO) && defined(AF_INET6)
3366 family = AF_UNSPEC;
3367 #else
3368 family = AF_INET;
3369 #endif
3370 }
3371 #ifdef HAVE_LOCAL_SOCKETS
3372 else if (EQ (tem, Qlocal))
3373 family = AF_LOCAL;
3374 #endif
3375 #ifdef AF_INET6
3376 else if (EQ (tem, Qipv6))
3377 family = AF_INET6;
3378 #endif
3379 else if (EQ (tem, Qipv4))
3380 family = AF_INET;
3381 else if (INTEGERP (tem))
3382 family = XINT (tem);
3383 else
3384 error ("Unknown address family");
3385
3386 ai.ai_family = family;
3387
3388 /* :service SERVICE -- string, integer (port number), or t (random port). */
3389 service = Fplist_get (contact, QCservice);
3390
3391 #ifdef HAVE_LOCAL_SOCKETS
3392 if (family == AF_LOCAL)
3393 {
3394 /* Host is not used. */
3395 host = Qnil;
3396 CHECK_STRING (service);
3397 bzero (&address_un, sizeof address_un);
3398 address_un.sun_family = AF_LOCAL;
3399 strncpy (address_un.sun_path, SDATA (service), sizeof address_un.sun_path);
3400 ai.ai_addr = (struct sockaddr *) &address_un;
3401 ai.ai_addrlen = sizeof address_un;
3402 goto open_socket;
3403 }
3404 #endif
3405
3406 /* :host HOST -- hostname, ip address, or 'local for localhost. */
3407 host = Fplist_get (contact, QChost);
3408 if (!NILP (host))
3409 {
3410 if (EQ (host, Qlocal))
3411 host = build_string ("localhost");
3412 CHECK_STRING (host);
3413 }
3414
3415 /* Slow down polling to every ten seconds.
3416 Some kernels have a bug which causes retrying connect to fail
3417 after a connect. Polling can interfere with gethostbyname too. */
3418 #ifdef POLL_FOR_INPUT
3419 if (socktype == SOCK_STREAM)
3420 {
3421 record_unwind_protect (unwind_stop_other_atimers, Qnil);
3422 bind_polling_period (10);
3423 }
3424 #endif
3425
3426 #ifdef HAVE_GETADDRINFO
3427 /* If we have a host, use getaddrinfo to resolve both host and service.
3428 Otherwise, use getservbyname to lookup the service. */
3429 if (!NILP (host))
3430 {
3431
3432 /* SERVICE can either be a string or int.
3433 Convert to a C string for later use by getaddrinfo. */
3434 if (EQ (service, Qt))
3435 portstring = "0";
3436 else if (INTEGERP (service))
3437 {
3438 sprintf (portbuf, "%ld", (long) XINT (service));
3439 portstring = portbuf;
3440 }
3441 else
3442 {
3443 CHECK_STRING (service);
3444 portstring = SDATA (service);
3445 }
3446
3447 immediate_quit = 1;
3448 QUIT;
3449 memset (&hints, 0, sizeof (hints));
3450 hints.ai_flags = 0;
3451 hints.ai_family = family;
3452 hints.ai_socktype = socktype;
3453 hints.ai_protocol = 0;
3454
3455 #ifdef HAVE_RES_INIT
3456 res_init ();
3457 #endif
3458
3459 ret = getaddrinfo (SDATA (host), portstring, &hints, &res);
3460 if (ret)
3461 #ifdef HAVE_GAI_STRERROR
3462 error ("%s/%s %s", SDATA (host), portstring, gai_strerror(ret));
3463 #else
3464 error ("%s/%s getaddrinfo error %d", SDATA (host), portstring, ret);
3465 #endif
3466 immediate_quit = 0;
3467
3468 goto open_socket;
3469 }
3470 #endif /* HAVE_GETADDRINFO */
3471
3472 /* We end up here if getaddrinfo is not defined, or in case no hostname
3473 has been specified (e.g. for a local server process). */
3474
3475 if (EQ (service, Qt))
3476 port = 0;
3477 else if (INTEGERP (service))
3478 port = htons ((unsigned short) XINT (service));
3479 else
3480 {
3481 struct servent *svc_info;
3482 CHECK_STRING (service);
3483 svc_info = getservbyname (SDATA (service),
3484 (socktype == SOCK_DGRAM ? "udp" : "tcp"));
3485 if (svc_info == 0)
3486 error ("Unknown service: %s", SDATA (service));
3487 port = svc_info->s_port;
3488 }
3489
3490 bzero (&address_in, sizeof address_in);
3491 address_in.sin_family = family;
3492 address_in.sin_addr.s_addr = INADDR_ANY;
3493 address_in.sin_port = port;
3494
3495 #ifndef HAVE_GETADDRINFO
3496 if (!NILP (host))
3497 {
3498 struct hostent *host_info_ptr;
3499
3500 /* gethostbyname may fail with TRY_AGAIN, but we don't honour that,
3501 as it may `hang' Emacs for a very long time. */
3502 immediate_quit = 1;
3503 QUIT;
3504
3505 #ifdef HAVE_RES_INIT
3506 res_init ();
3507 #endif
3508
3509 host_info_ptr = gethostbyname (SDATA (host));
3510 immediate_quit = 0;
3511
3512 if (host_info_ptr)
3513 {
3514 bcopy (host_info_ptr->h_addr, (char *) &address_in.sin_addr,
3515 host_info_ptr->h_length);
3516 family = host_info_ptr->h_addrtype;
3517 address_in.sin_family = family;
3518 }
3519 else
3520 /* Attempt to interpret host as numeric inet address */
3521 {
3522 unsigned long numeric_addr;
3523 numeric_addr = inet_addr ((char *) SDATA (host));
3524 if (numeric_addr == -1)
3525 error ("Unknown host \"%s\"", SDATA (host));
3526
3527 bcopy ((char *)&numeric_addr, (char *) &address_in.sin_addr,
3528 sizeof (address_in.sin_addr));
3529 }
3530
3531 }
3532 #endif /* not HAVE_GETADDRINFO */
3533
3534 ai.ai_family = family;
3535 ai.ai_addr = (struct sockaddr *) &address_in;
3536 ai.ai_addrlen = sizeof address_in;
3537
3538 open_socket:
3539
3540 /* Do this in case we never enter the for-loop below. */
3541 count1 = SPECPDL_INDEX ();
3542 s = -1;
3543
3544 for (lres = res; lres; lres = lres->ai_next)
3545 {
3546 int optn, optbits;
3547
3548 retry_connect:
3549
3550 s = socket (lres->ai_family, lres->ai_socktype, lres->ai_protocol);
3551 if (s < 0)
3552 {
3553 xerrno = errno;
3554 continue;
3555 }
3556
3557 #ifdef DATAGRAM_SOCKETS
3558 if (!is_server && socktype == SOCK_DGRAM)
3559 break;
3560 #endif /* DATAGRAM_SOCKETS */
3561
3562 #ifdef NON_BLOCKING_CONNECT
3563 if (is_non_blocking_client)
3564 {
3565 #ifdef O_NONBLOCK
3566 ret = fcntl (s, F_SETFL, O_NONBLOCK);
3567 #else
3568 ret = fcntl (s, F_SETFL, O_NDELAY);
3569 #endif
3570 if (ret < 0)
3571 {
3572 xerrno = errno;
3573 emacs_close (s);
3574 s = -1;
3575 continue;
3576 }
3577 }
3578 #endif
3579
3580 /* Make us close S if quit. */
3581 record_unwind_protect (close_file_unwind, make_number (s));
3582
3583 /* Parse network options in the arg list.
3584 We simply ignore anything which isn't a known option (including other keywords).
3585 An error is signaled if setting a known option fails. */
3586 for (optn = optbits = 0; optn < nargs-1; optn += 2)
3587 optbits |= set_socket_option (s, args[optn], args[optn+1]);
3588
3589 if (is_server)
3590 {
3591 /* Configure as a server socket. */
3592
3593 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3594 explicit :reuseaddr key to override this. */
3595 #ifdef HAVE_LOCAL_SOCKETS
3596 if (family != AF_LOCAL)
3597 #endif
3598 if (!(optbits & (1 << OPIX_REUSEADDR)))
3599 {
3600 int optval = 1;
3601 if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval))
3602 report_file_error ("Cannot set reuse option on server socket", Qnil);
3603 }
3604
3605 if (bind (s, lres->ai_addr, lres->ai_addrlen))
3606 report_file_error ("Cannot bind server socket", Qnil);
3607
3608 #ifdef HAVE_GETSOCKNAME
3609 if (EQ (service, Qt))
3610 {
3611 struct sockaddr_in sa1;
3612 int len1 = sizeof (sa1);
3613 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3614 {
3615 ((struct sockaddr_in *)(lres->ai_addr))->sin_port = sa1.sin_port;
3616 service = make_number (ntohs (sa1.sin_port));
3617 contact = Fplist_put (contact, QCservice, service);
3618 }
3619 }
3620 #endif
3621
3622 if (socktype == SOCK_STREAM && listen (s, backlog))
3623 report_file_error ("Cannot listen on server socket", Qnil);
3624
3625 break;
3626 }
3627
3628 immediate_quit = 1;
3629 QUIT;
3630
3631 /* This turns off all alarm-based interrupts; the
3632 bind_polling_period call above doesn't always turn all the
3633 short-interval ones off, especially if interrupt_input is
3634 set.
3635
3636 It'd be nice to be able to control the connect timeout
3637 though. Would non-blocking connect calls be portable?
3638
3639 This used to be conditioned by HAVE_GETADDRINFO. Why? */
3640
3641 turn_on_atimers (0);
3642
3643 ret = connect (s, lres->ai_addr, lres->ai_addrlen);
3644 xerrno = errno;
3645
3646 turn_on_atimers (1);
3647
3648 if (ret == 0 || xerrno == EISCONN)
3649 {
3650 /* The unwind-protect will be discarded afterwards.
3651 Likewise for immediate_quit. */
3652 break;
3653 }
3654
3655 #ifdef NON_BLOCKING_CONNECT
3656 #ifdef EINPROGRESS
3657 if (is_non_blocking_client && xerrno == EINPROGRESS)
3658 break;
3659 #else
3660 #ifdef EWOULDBLOCK
3661 if (is_non_blocking_client && xerrno == EWOULDBLOCK)
3662 break;
3663 #endif
3664 #endif
3665 #endif
3666
3667 immediate_quit = 0;
3668
3669 /* Discard the unwind protect closing S. */
3670 specpdl_ptr = specpdl + count1;
3671 emacs_close (s);
3672 s = -1;
3673
3674 if (xerrno == EINTR)
3675 goto retry_connect;
3676 }
3677
3678 if (s >= 0)
3679 {
3680 #ifdef DATAGRAM_SOCKETS
3681 if (socktype == SOCK_DGRAM)
3682 {
3683 if (datagram_address[s].sa)
3684 abort ();
3685 datagram_address[s].sa = (struct sockaddr *) xmalloc (lres->ai_addrlen);
3686 datagram_address[s].len = lres->ai_addrlen;
3687 if (is_server)
3688 {
3689 Lisp_Object remote;
3690 bzero (datagram_address[s].sa, lres->ai_addrlen);
3691 if (remote = Fplist_get (contact, QCremote), !NILP (remote))
3692 {
3693 int rfamily, rlen;
3694 rlen = get_lisp_to_sockaddr_size (remote, &rfamily);
3695 if (rfamily == lres->ai_family && rlen == lres->ai_addrlen)
3696 conv_lisp_to_sockaddr (rfamily, remote,
3697 datagram_address[s].sa, rlen);
3698 }
3699 }
3700 else
3701 bcopy (lres->ai_addr, datagram_address[s].sa, lres->ai_addrlen);
3702 }
3703 #endif
3704 contact = Fplist_put (contact, QCaddress,
3705 conv_sockaddr_to_lisp (lres->ai_addr, lres->ai_addrlen));
3706 #ifdef HAVE_GETSOCKNAME
3707 if (!is_server)
3708 {
3709 struct sockaddr_in sa1;
3710 int len1 = sizeof (sa1);
3711 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3712 contact = Fplist_put (contact, QClocal,
3713 conv_sockaddr_to_lisp (&sa1, len1));
3714 }
3715 #endif
3716 }
3717
3718 immediate_quit = 0;
3719
3720 #ifdef HAVE_GETADDRINFO
3721 if (res != &ai)
3722 {
3723 BLOCK_INPUT;
3724 freeaddrinfo (res);
3725 UNBLOCK_INPUT;
3726 }
3727 #endif
3728
3729 /* Discard the unwind protect for closing S, if any. */
3730 specpdl_ptr = specpdl + count1;
3731
3732 /* Unwind bind_polling_period and request_sigio. */
3733 unbind_to (count, Qnil);
3734
3735 if (s < 0)
3736 {
3737 /* If non-blocking got this far - and failed - assume non-blocking is
3738 not supported after all. This is probably a wrong assumption, but
3739 the normal blocking calls to open-network-stream handles this error
3740 better. */
3741 if (is_non_blocking_client)
3742 return Qnil;
3743
3744 errno = xerrno;
3745 if (is_server)
3746 report_file_error ("make server process failed", contact);
3747 else
3748 report_file_error ("make client process failed", contact);
3749 }
3750
3751 inch = s;
3752 outch = s;
3753
3754 if (!NILP (buffer))
3755 buffer = Fget_buffer_create (buffer);
3756 proc = make_process (name);
3757
3758 chan_process[inch] = proc;
3759
3760 #ifdef O_NONBLOCK
3761 fcntl (inch, F_SETFL, O_NONBLOCK);
3762 #else
3763 #ifdef O_NDELAY
3764 fcntl (inch, F_SETFL, O_NDELAY);
3765 #endif
3766 #endif
3767
3768 p = XPROCESS (proc);
3769
3770 p->childp = contact;
3771 p->plist = Fcopy_sequence (Fplist_get (contact, QCplist));
3772 p->type = Qnetwork;
3773
3774 p->buffer = buffer;
3775 p->sentinel = sentinel;
3776 p->filter = filter;
3777 p->log = Fplist_get (contact, QClog);
3778 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
3779 p->kill_without_query = 1;
3780 if ((tem = Fplist_get (contact, QCstop), !NILP (tem)))
3781 p->command = Qt;
3782 p->pid = 0;
3783 p->infd = inch;
3784 p->outfd = outch;
3785 if (is_server && socktype == SOCK_STREAM)
3786 p->status = Qlisten;
3787
3788 /* Make the process marker point into the process buffer (if any). */
3789 if (BUFFERP (buffer))
3790 set_marker_both (p->mark, buffer,
3791 BUF_ZV (XBUFFER (buffer)),
3792 BUF_ZV_BYTE (XBUFFER (buffer)));
3793
3794 #ifdef NON_BLOCKING_CONNECT
3795 if (is_non_blocking_client)
3796 {
3797 /* We may get here if connect did succeed immediately. However,
3798 in that case, we still need to signal this like a non-blocking
3799 connection. */
3800 p->status = Qconnect;
3801 if (!FD_ISSET (inch, &connect_wait_mask))
3802 {
3803 FD_SET (inch, &connect_wait_mask);
3804 num_pending_connects++;
3805 }
3806 }
3807 else
3808 #endif
3809 /* A server may have a client filter setting of Qt, but it must
3810 still listen for incoming connects unless it is stopped. */
3811 if ((!EQ (p->filter, Qt) && !EQ (p->command, Qt))
3812 || (EQ (p->status, Qlisten) && NILP (p->command)))
3813 {
3814 FD_SET (inch, &input_wait_mask);
3815 FD_SET (inch, &non_keyboard_wait_mask);
3816 }
3817
3818 if (inch > max_process_desc)
3819 max_process_desc = inch;
3820
3821 tem = Fplist_member (contact, QCcoding);
3822 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
3823 tem = Qnil; /* No error message (too late!). */
3824
3825 {
3826 /* Setup coding systems for communicating with the network stream. */
3827 struct gcpro gcpro1;
3828 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3829 Lisp_Object coding_systems = Qt;
3830 Lisp_Object args[5], val;
3831
3832 if (!NILP (tem))
3833 {
3834 val = XCAR (XCDR (tem));
3835 if (CONSP (val))
3836 val = XCAR (val);
3837 }
3838 else if (!NILP (Vcoding_system_for_read))
3839 val = Vcoding_system_for_read;
3840 else if ((!NILP (buffer) && NILP (XBUFFER (buffer)->enable_multibyte_characters))
3841 || (NILP (buffer) && NILP (buffer_defaults.enable_multibyte_characters)))
3842 /* We dare not decode end-of-line format by setting VAL to
3843 Qraw_text, because the existing Emacs Lisp libraries
3844 assume that they receive bare code including a sequene of
3845 CR LF. */
3846 val = Qnil;
3847 else
3848 {
3849 if (NILP (host) || NILP (service))
3850 coding_systems = Qnil;
3851 else
3852 {
3853 args[0] = Qopen_network_stream, args[1] = name,
3854 args[2] = buffer, args[3] = host, args[4] = service;
3855 GCPRO1 (proc);
3856 coding_systems = Ffind_operation_coding_system (5, args);
3857 UNGCPRO;
3858 }
3859 if (CONSP (coding_systems))
3860 val = XCAR (coding_systems);
3861 else if (CONSP (Vdefault_process_coding_system))
3862 val = XCAR (Vdefault_process_coding_system);
3863 else
3864 val = Qnil;
3865 }
3866 p->decode_coding_system = val;
3867
3868 if (!NILP (tem))
3869 {
3870 val = XCAR (XCDR (tem));
3871 if (CONSP (val))
3872 val = XCDR (val);
3873 }
3874 else if (!NILP (Vcoding_system_for_write))
3875 val = Vcoding_system_for_write;
3876 else if (NILP (current_buffer->enable_multibyte_characters))
3877 val = Qnil;
3878 else
3879 {
3880 if (EQ (coding_systems, Qt))
3881 {
3882 if (NILP (host) || NILP (service))
3883 coding_systems = Qnil;
3884 else
3885 {
3886 args[0] = Qopen_network_stream, args[1] = name,
3887 args[2] = buffer, args[3] = host, args[4] = service;
3888 GCPRO1 (proc);
3889 coding_systems = Ffind_operation_coding_system (5, args);
3890 UNGCPRO;
3891 }
3892 }
3893 if (CONSP (coding_systems))
3894 val = XCDR (coding_systems);
3895 else if (CONSP (Vdefault_process_coding_system))
3896 val = XCDR (Vdefault_process_coding_system);
3897 else
3898 val = Qnil;
3899 }
3900 p->encode_coding_system = val;
3901 }
3902 setup_process_coding_systems (proc);
3903
3904 p->decoding_buf = make_uninit_string (0);
3905 p->decoding_carryover = 0;
3906 p->encoding_buf = make_uninit_string (0);
3907
3908 p->inherit_coding_system_flag
3909 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
3910
3911 UNGCPRO;
3912 return proc;
3913 }
3914 #endif /* HAVE_SOCKETS */
3915
3916 \f
3917 #if defined(HAVE_SOCKETS) && defined(HAVE_NET_IF_H) && defined(HAVE_SYS_IOCTL_H)
3918
3919 #ifdef SIOCGIFCONF
3920 DEFUN ("network-interface-list", Fnetwork_interface_list, Snetwork_interface_list, 0, 0, 0,
3921 doc: /* Return an alist of all network interfaces and their network address.
3922 Each element is a cons, the car of which is a string containing the
3923 interface name, and the cdr is the network address in internal
3924 format; see the description of ADDRESS in `make-network-process'. */)
3925 ()
3926 {
3927 struct ifconf ifconf;
3928 struct ifreq *ifreqs = NULL;
3929 int ifaces = 0;
3930 int buf_size, s;
3931 Lisp_Object res;
3932
3933 s = socket (AF_INET, SOCK_STREAM, 0);
3934 if (s < 0)
3935 return Qnil;
3936
3937 again:
3938 ifaces += 25;
3939 buf_size = ifaces * sizeof(ifreqs[0]);
3940 ifreqs = (struct ifreq *)xrealloc(ifreqs, buf_size);
3941 if (!ifreqs)
3942 {
3943 close (s);
3944 return Qnil;
3945 }
3946
3947 ifconf.ifc_len = buf_size;
3948 ifconf.ifc_req = ifreqs;
3949 if (ioctl (s, SIOCGIFCONF, &ifconf))
3950 {
3951 close (s);
3952 return Qnil;
3953 }
3954
3955 if (ifconf.ifc_len == buf_size)
3956 goto again;
3957
3958 close (s);
3959 ifaces = ifconf.ifc_len / sizeof (ifreqs[0]);
3960
3961 res = Qnil;
3962 while (--ifaces >= 0)
3963 {
3964 struct ifreq *ifq = &ifreqs[ifaces];
3965 char namebuf[sizeof (ifq->ifr_name) + 1];
3966 if (ifq->ifr_addr.sa_family != AF_INET)
3967 continue;
3968 bcopy (ifq->ifr_name, namebuf, sizeof (ifq->ifr_name));
3969 namebuf[sizeof (ifq->ifr_name)] = 0;
3970 res = Fcons (Fcons (build_string (namebuf),
3971 conv_sockaddr_to_lisp (&ifq->ifr_addr,
3972 sizeof (struct sockaddr))),
3973 res);
3974 }
3975
3976 return res;
3977 }
3978 #endif /* SIOCGIFCONF */
3979
3980 #if defined(SIOCGIFADDR) || defined(SIOCGIFHWADDR) || defined(SIOCGIFFLAGS)
3981
3982 struct ifflag_def {
3983 int flag_bit;
3984 char *flag_sym;
3985 };
3986
3987 static struct ifflag_def ifflag_table[] = {
3988 #ifdef IFF_UP
3989 { IFF_UP, "up" },
3990 #endif
3991 #ifdef IFF_BROADCAST
3992 { IFF_BROADCAST, "broadcast" },
3993 #endif
3994 #ifdef IFF_DEBUG
3995 { IFF_DEBUG, "debug" },
3996 #endif
3997 #ifdef IFF_LOOPBACK
3998 { IFF_LOOPBACK, "loopback" },
3999 #endif
4000 #ifdef IFF_POINTOPOINT
4001 { IFF_POINTOPOINT, "pointopoint" },
4002 #endif
4003 #ifdef IFF_RUNNING
4004 { IFF_RUNNING, "running" },
4005 #endif
4006 #ifdef IFF_NOARP
4007 { IFF_NOARP, "noarp" },
4008 #endif
4009 #ifdef IFF_PROMISC
4010 { IFF_PROMISC, "promisc" },
4011 #endif
4012 #ifdef IFF_NOTRAILERS
4013 { IFF_NOTRAILERS, "notrailers" },
4014 #endif
4015 #ifdef IFF_ALLMULTI
4016 { IFF_ALLMULTI, "allmulti" },
4017 #endif
4018 #ifdef IFF_MASTER
4019 { IFF_MASTER, "master" },
4020 #endif
4021 #ifdef IFF_SLAVE
4022 { IFF_SLAVE, "slave" },
4023 #endif
4024 #ifdef IFF_MULTICAST
4025 { IFF_MULTICAST, "multicast" },
4026 #endif
4027 #ifdef IFF_PORTSEL
4028 { IFF_PORTSEL, "portsel" },
4029 #endif
4030 #ifdef IFF_AUTOMEDIA
4031 { IFF_AUTOMEDIA, "automedia" },
4032 #endif
4033 #ifdef IFF_DYNAMIC
4034 { IFF_DYNAMIC, "dynamic" },
4035 #endif
4036 #ifdef IFF_OACTIVE
4037 { IFF_OACTIVE, "oactive" }, /* OpenBSD: transmission in progress */
4038 #endif
4039 #ifdef IFF_SIMPLEX
4040 { IFF_SIMPLEX, "simplex" }, /* OpenBSD: can't hear own transmissions */
4041 #endif
4042 #ifdef IFF_LINK0
4043 { IFF_LINK0, "link0" }, /* OpenBSD: per link layer defined bit */
4044 #endif
4045 #ifdef IFF_LINK1
4046 { IFF_LINK1, "link1" }, /* OpenBSD: per link layer defined bit */
4047 #endif
4048 #ifdef IFF_LINK2
4049 { IFF_LINK2, "link2" }, /* OpenBSD: per link layer defined bit */
4050 #endif
4051 { 0, 0 }
4052 };
4053
4054 DEFUN ("network-interface-info", Fnetwork_interface_info, Snetwork_interface_info, 1, 1, 0,
4055 doc: /* Return information about network interface named IFNAME.
4056 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
4057 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
4058 NETMASK is the layer 3 network mask, HWADDR is the layer 2 addres, and
4059 FLAGS is the current flags of the interface. */)
4060 (ifname)
4061 Lisp_Object ifname;
4062 {
4063 struct ifreq rq;
4064 Lisp_Object res = Qnil;
4065 Lisp_Object elt;
4066 int s;
4067 int any = 0;
4068
4069 CHECK_STRING (ifname);
4070
4071 bzero (rq.ifr_name, sizeof rq.ifr_name);
4072 strncpy (rq.ifr_name, SDATA (ifname), sizeof (rq.ifr_name));
4073
4074 s = socket (AF_INET, SOCK_STREAM, 0);
4075 if (s < 0)
4076 return Qnil;
4077
4078 elt = Qnil;
4079 #if defined(SIOCGIFFLAGS) && defined(HAVE_STRUCT_IFREQ_IFR_FLAGS)
4080 if (ioctl (s, SIOCGIFFLAGS, &rq) == 0)
4081 {
4082 int flags = rq.ifr_flags;
4083 struct ifflag_def *fp;
4084 int fnum;
4085
4086 any++;
4087 for (fp = ifflag_table; flags != 0 && fp->flag_sym; fp++)
4088 {
4089 if (flags & fp->flag_bit)
4090 {
4091 elt = Fcons (intern (fp->flag_sym), elt);
4092 flags -= fp->flag_bit;
4093 }
4094 }
4095 for (fnum = 0; flags && fnum < 32; fnum++)
4096 {
4097 if (flags & (1 << fnum))
4098 {
4099 elt = Fcons (make_number (fnum), elt);
4100 }
4101 }
4102 }
4103 #endif
4104 res = Fcons (elt, res);
4105
4106 elt = Qnil;
4107 #if defined(SIOCGIFHWADDR) && defined(HAVE_STRUCT_IFREQ_IFR_HWADDR)
4108 if (ioctl (s, SIOCGIFHWADDR, &rq) == 0)
4109 {
4110 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
4111 register struct Lisp_Vector *p = XVECTOR (hwaddr);
4112 int n;
4113
4114 any++;
4115 for (n = 0; n < 6; n++)
4116 p->contents[n] = make_number (((unsigned char *)&rq.ifr_hwaddr.sa_data[0])[n]);
4117 elt = Fcons (make_number (rq.ifr_hwaddr.sa_family), hwaddr);
4118 }
4119 #endif
4120 res = Fcons (elt, res);
4121
4122 elt = Qnil;
4123 #if defined(SIOCGIFNETMASK) && (defined(HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined(HAVE_STRUCT_IFREQ_IFR_ADDR))
4124 if (ioctl (s, SIOCGIFNETMASK, &rq) == 0)
4125 {
4126 any++;
4127 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
4128 elt = conv_sockaddr_to_lisp (&rq.ifr_netmask, sizeof (rq.ifr_netmask));
4129 #else
4130 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4131 #endif
4132 }
4133 #endif
4134 res = Fcons (elt, res);
4135
4136 elt = Qnil;
4137 #if defined(SIOCGIFBRDADDR) && defined(HAVE_STRUCT_IFREQ_IFR_BROADADDR)
4138 if (ioctl (s, SIOCGIFBRDADDR, &rq) == 0)
4139 {
4140 any++;
4141 elt = conv_sockaddr_to_lisp (&rq.ifr_broadaddr, sizeof (rq.ifr_broadaddr));
4142 }
4143 #endif
4144 res = Fcons (elt, res);
4145
4146 elt = Qnil;
4147 #if defined(SIOCGIFADDR) && defined(HAVE_STRUCT_IFREQ_IFR_ADDR)
4148 if (ioctl (s, SIOCGIFADDR, &rq) == 0)
4149 {
4150 any++;
4151 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4152 }
4153 #endif
4154 res = Fcons (elt, res);
4155
4156 close (s);
4157
4158 return any ? res : Qnil;
4159 }
4160 #endif
4161 #endif /* HAVE_SOCKETS */
4162
4163 /* Turn off input and output for process PROC. */
4164
4165 void
4166 deactivate_process (proc)
4167 Lisp_Object proc;
4168 {
4169 register int inchannel, outchannel;
4170 register struct Lisp_Process *p = XPROCESS (proc);
4171
4172 inchannel = p->infd;
4173 outchannel = p->outfd;
4174
4175 #ifdef ADAPTIVE_READ_BUFFERING
4176 if (p->read_output_delay > 0)
4177 {
4178 if (--process_output_delay_count < 0)
4179 process_output_delay_count = 0;
4180 p->read_output_delay = 0;
4181 p->read_output_skip = 0;
4182 }
4183 #endif
4184
4185 if (inchannel >= 0)
4186 {
4187 /* Beware SIGCHLD hereabouts. */
4188 flush_pending_output (inchannel);
4189 emacs_close (inchannel);
4190 if (outchannel >= 0 && outchannel != inchannel)
4191 emacs_close (outchannel);
4192
4193 p->infd = -1;
4194 p->outfd = -1;
4195 #ifdef DATAGRAM_SOCKETS
4196 if (DATAGRAM_CHAN_P (inchannel))
4197 {
4198 xfree (datagram_address[inchannel].sa);
4199 datagram_address[inchannel].sa = 0;
4200 datagram_address[inchannel].len = 0;
4201 }
4202 #endif
4203 chan_process[inchannel] = Qnil;
4204 FD_CLR (inchannel, &input_wait_mask);
4205 FD_CLR (inchannel, &non_keyboard_wait_mask);
4206 #ifdef NON_BLOCKING_CONNECT
4207 if (FD_ISSET (inchannel, &connect_wait_mask))
4208 {
4209 FD_CLR (inchannel, &connect_wait_mask);
4210 if (--num_pending_connects < 0)
4211 abort ();
4212 }
4213 #endif
4214 if (inchannel == max_process_desc)
4215 {
4216 int i;
4217 /* We just closed the highest-numbered process input descriptor,
4218 so recompute the highest-numbered one now. */
4219 max_process_desc = 0;
4220 for (i = 0; i < MAXDESC; i++)
4221 if (!NILP (chan_process[i]))
4222 max_process_desc = i;
4223 }
4224 }
4225 }
4226
4227 /* Close all descriptors currently in use for communication
4228 with subprocess. This is used in a newly-forked subprocess
4229 to get rid of irrelevant descriptors. */
4230
4231 void
4232 close_process_descs ()
4233 {
4234 #ifndef WINDOWSNT
4235 int i;
4236 for (i = 0; i < MAXDESC; i++)
4237 {
4238 Lisp_Object process;
4239 process = chan_process[i];
4240 if (!NILP (process))
4241 {
4242 int in = XPROCESS (process)->infd;
4243 int out = XPROCESS (process)->outfd;
4244 if (in >= 0)
4245 emacs_close (in);
4246 if (out >= 0 && in != out)
4247 emacs_close (out);
4248 }
4249 }
4250 #endif
4251 }
4252 \f
4253 DEFUN ("accept-process-output", Faccept_process_output, Saccept_process_output,
4254 0, 4, 0,
4255 doc: /* Allow any pending output from subprocesses to be read by Emacs.
4256 It is read into the process' buffers or given to their filter functions.
4257 Non-nil arg PROCESS means do not return until some output has been received
4258 from PROCESS.
4259
4260 Non-nil second arg SECONDS and third arg MILLISEC are number of seconds
4261 and milliseconds to wait; return after that much time whether or not
4262 there is any subprocess output. If SECONDS is a floating point number,
4263 it specifies a fractional number of seconds to wait.
4264 The MILLISEC argument is obsolete and should be avoided.
4265
4266 If optional fourth arg JUST-THIS-ONE is non-nil, only accept output
4267 from PROCESS, suspending reading output from other processes.
4268 If JUST-THIS-ONE is an integer, don't run any timers either.
4269 Return non-nil if we received any output before the timeout expired. */)
4270 (process, seconds, millisec, just_this_one)
4271 register Lisp_Object process, seconds, millisec, just_this_one;
4272 {
4273 int secs, usecs = 0;
4274
4275 if (! NILP (process))
4276 CHECK_PROCESS (process);
4277 else
4278 just_this_one = Qnil;
4279
4280 if (!NILP (millisec))
4281 { /* Obsolete calling convention using integers rather than floats. */
4282 CHECK_NUMBER (millisec);
4283 if (NILP (seconds))
4284 seconds = make_float (XINT (millisec) / 1000.0);
4285 else
4286 {
4287 CHECK_NUMBER (seconds);
4288 seconds = make_float (XINT (millisec) / 1000.0 + XINT (seconds));
4289 }
4290 }
4291
4292 if (!NILP (seconds))
4293 {
4294 if (INTEGERP (seconds))
4295 secs = XINT (seconds);
4296 else if (FLOATP (seconds))
4297 {
4298 double timeout = XFLOAT_DATA (seconds);
4299 secs = (int) timeout;
4300 usecs = (int) ((timeout - (double) secs) * 1000000);
4301 }
4302 else
4303 wrong_type_argument (Qnumberp, seconds);
4304
4305 if (secs < 0 || (secs == 0 && usecs == 0))
4306 secs = -1, usecs = 0;
4307 }
4308 else
4309 secs = NILP (process) ? -1 : 0;
4310
4311 return
4312 (wait_reading_process_output (secs, usecs, 0, 0,
4313 Qnil,
4314 !NILP (process) ? XPROCESS (process) : NULL,
4315 NILP (just_this_one) ? 0 :
4316 !INTEGERP (just_this_one) ? 1 : -1)
4317 ? Qt : Qnil);
4318 }
4319
4320 /* Accept a connection for server process SERVER on CHANNEL. */
4321
4322 static int connect_counter = 0;
4323
4324 static void
4325 server_accept_connection (server, channel)
4326 Lisp_Object server;
4327 int channel;
4328 {
4329 Lisp_Object proc, caller, name, buffer;
4330 Lisp_Object contact, host, service;
4331 struct Lisp_Process *ps= XPROCESS (server);
4332 struct Lisp_Process *p;
4333 int s;
4334 union u_sockaddr {
4335 struct sockaddr sa;
4336 struct sockaddr_in in;
4337 #ifdef AF_INET6
4338 struct sockaddr_in6 in6;
4339 #endif
4340 #ifdef HAVE_LOCAL_SOCKETS
4341 struct sockaddr_un un;
4342 #endif
4343 } saddr;
4344 int len = sizeof saddr;
4345
4346 s = accept (channel, &saddr.sa, &len);
4347
4348 if (s < 0)
4349 {
4350 int code = errno;
4351
4352 if (code == EAGAIN)
4353 return;
4354 #ifdef EWOULDBLOCK
4355 if (code == EWOULDBLOCK)
4356 return;
4357 #endif
4358
4359 if (!NILP (ps->log))
4360 call3 (ps->log, server, Qnil,
4361 concat3 (build_string ("accept failed with code"),
4362 Fnumber_to_string (make_number (code)),
4363 build_string ("\n")));
4364 return;
4365 }
4366
4367 connect_counter++;
4368
4369 /* Setup a new process to handle the connection. */
4370
4371 /* Generate a unique identification of the caller, and build contact
4372 information for this process. */
4373 host = Qt;
4374 service = Qnil;
4375 switch (saddr.sa.sa_family)
4376 {
4377 case AF_INET:
4378 {
4379 Lisp_Object args[5];
4380 unsigned char *ip = (unsigned char *)&saddr.in.sin_addr.s_addr;
4381 args[0] = build_string ("%d.%d.%d.%d");
4382 args[1] = make_number (*ip++);
4383 args[2] = make_number (*ip++);
4384 args[3] = make_number (*ip++);
4385 args[4] = make_number (*ip++);
4386 host = Fformat (5, args);
4387 service = make_number (ntohs (saddr.in.sin_port));
4388
4389 args[0] = build_string (" <%s:%d>");
4390 args[1] = host;
4391 args[2] = service;
4392 caller = Fformat (3, args);
4393 }
4394 break;
4395
4396 #ifdef AF_INET6
4397 case AF_INET6:
4398 {
4399 Lisp_Object args[9];
4400 uint16_t *ip6 = (uint16_t *)&saddr.in6.sin6_addr;
4401 int i;
4402 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
4403 for (i = 0; i < 8; i++)
4404 args[i+1] = make_number (ntohs(ip6[i]));
4405 host = Fformat (9, args);
4406 service = make_number (ntohs (saddr.in.sin_port));
4407
4408 args[0] = build_string (" <[%s]:%d>");
4409 args[1] = host;
4410 args[2] = service;
4411 caller = Fformat (3, args);
4412 }
4413 break;
4414 #endif
4415
4416 #ifdef HAVE_LOCAL_SOCKETS
4417 case AF_LOCAL:
4418 #endif
4419 default:
4420 caller = Fnumber_to_string (make_number (connect_counter));
4421 caller = concat3 (build_string (" <"), caller, build_string (">"));
4422 break;
4423 }
4424
4425 /* Create a new buffer name for this process if it doesn't have a
4426 filter. The new buffer name is based on the buffer name or
4427 process name of the server process concatenated with the caller
4428 identification. */
4429
4430 if (!NILP (ps->filter) && !EQ (ps->filter, Qt))
4431 buffer = Qnil;
4432 else
4433 {
4434 buffer = ps->buffer;
4435 if (!NILP (buffer))
4436 buffer = Fbuffer_name (buffer);
4437 else
4438 buffer = ps->name;
4439 if (!NILP (buffer))
4440 {
4441 buffer = concat2 (buffer, caller);
4442 buffer = Fget_buffer_create (buffer);
4443 }
4444 }
4445
4446 /* Generate a unique name for the new server process. Combine the
4447 server process name with the caller identification. */
4448
4449 name = concat2 (ps->name, caller);
4450 proc = make_process (name);
4451
4452 chan_process[s] = proc;
4453
4454 #ifdef O_NONBLOCK
4455 fcntl (s, F_SETFL, O_NONBLOCK);
4456 #else
4457 #ifdef O_NDELAY
4458 fcntl (s, F_SETFL, O_NDELAY);
4459 #endif
4460 #endif
4461
4462 p = XPROCESS (proc);
4463
4464 /* Build new contact information for this setup. */
4465 contact = Fcopy_sequence (ps->childp);
4466 contact = Fplist_put (contact, QCserver, Qnil);
4467 contact = Fplist_put (contact, QChost, host);
4468 if (!NILP (service))
4469 contact = Fplist_put (contact, QCservice, service);
4470 contact = Fplist_put (contact, QCremote,
4471 conv_sockaddr_to_lisp (&saddr.sa, len));
4472 #ifdef HAVE_GETSOCKNAME
4473 len = sizeof saddr;
4474 if (getsockname (s, &saddr.sa, &len) == 0)
4475 contact = Fplist_put (contact, QClocal,
4476 conv_sockaddr_to_lisp (&saddr.sa, len));
4477 #endif
4478
4479 p->childp = contact;
4480 p->plist = Fcopy_sequence (ps->plist);
4481 p->type = Qnetwork;
4482
4483 p->buffer = buffer;
4484 p->sentinel = ps->sentinel;
4485 p->filter = ps->filter;
4486 p->command = Qnil;
4487 p->pid = 0;
4488 p->infd = s;
4489 p->outfd = s;
4490 p->status = Qrun;
4491
4492 /* Client processes for accepted connections are not stopped initially. */
4493 if (!EQ (p->filter, Qt))
4494 {
4495 FD_SET (s, &input_wait_mask);
4496 FD_SET (s, &non_keyboard_wait_mask);
4497 }
4498
4499 if (s > max_process_desc)
4500 max_process_desc = s;
4501
4502 /* Setup coding system for new process based on server process.
4503 This seems to be the proper thing to do, as the coding system
4504 of the new process should reflect the settings at the time the
4505 server socket was opened; not the current settings. */
4506
4507 p->decode_coding_system = ps->decode_coding_system;
4508 p->encode_coding_system = ps->encode_coding_system;
4509 setup_process_coding_systems (proc);
4510
4511 p->decoding_buf = make_uninit_string (0);
4512 p->decoding_carryover = 0;
4513 p->encoding_buf = make_uninit_string (0);
4514
4515 p->inherit_coding_system_flag
4516 = (NILP (buffer) ? 0 : ps->inherit_coding_system_flag);
4517
4518 if (!NILP (ps->log))
4519 call3 (ps->log, server, proc,
4520 concat3 (build_string ("accept from "),
4521 (STRINGP (host) ? host : build_string ("-")),
4522 build_string ("\n")));
4523
4524 if (!NILP (p->sentinel))
4525 exec_sentinel (proc,
4526 concat3 (build_string ("open from "),
4527 (STRINGP (host) ? host : build_string ("-")),
4528 build_string ("\n")));
4529 }
4530
4531 /* This variable is different from waiting_for_input in keyboard.c.
4532 It is used to communicate to a lisp process-filter/sentinel (via the
4533 function Fwaiting_for_user_input_p below) whether Emacs was waiting
4534 for user-input when that process-filter was called.
4535 waiting_for_input cannot be used as that is by definition 0 when
4536 lisp code is being evalled.
4537 This is also used in record_asynch_buffer_change.
4538 For that purpose, this must be 0
4539 when not inside wait_reading_process_output. */
4540 static int waiting_for_user_input_p;
4541
4542 static Lisp_Object
4543 wait_reading_process_output_unwind (data)
4544 Lisp_Object data;
4545 {
4546 waiting_for_user_input_p = XINT (data);
4547 return Qnil;
4548 }
4549
4550 /* This is here so breakpoints can be put on it. */
4551 static void
4552 wait_reading_process_output_1 ()
4553 {
4554 }
4555
4556 /* Use a wrapper around select to work around a bug in gdb 5.3.
4557 Normally, the wrapper is optimzed away by inlining.
4558
4559 If emacs is stopped inside select, the gdb backtrace doesn't
4560 show the function which called select, so it is practically
4561 impossible to step through wait_reading_process_output. */
4562
4563 #ifndef select
4564 static INLINE int
4565 select_wrapper (n, rfd, wfd, xfd, tmo)
4566 int n;
4567 SELECT_TYPE *rfd, *wfd, *xfd;
4568 EMACS_TIME *tmo;
4569 {
4570 return select (n, rfd, wfd, xfd, tmo);
4571 }
4572 #define select select_wrapper
4573 #endif
4574
4575 /* Read and dispose of subprocess output while waiting for timeout to
4576 elapse and/or keyboard input to be available.
4577
4578 TIME_LIMIT is:
4579 timeout in seconds, or
4580 zero for no limit, or
4581 -1 means gobble data immediately available but don't wait for any.
4582
4583 MICROSECS is:
4584 an additional duration to wait, measured in microseconds.
4585 If this is nonzero and time_limit is 0, then the timeout
4586 consists of MICROSECS only.
4587
4588 READ_KBD is a lisp value:
4589 0 to ignore keyboard input, or
4590 1 to return when input is available, or
4591 -1 meaning caller will actually read the input, so don't throw to
4592 the quit handler, or
4593
4594 DO_DISPLAY != 0 means redisplay should be done to show subprocess
4595 output that arrives.
4596
4597 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4598 (and gobble terminal input into the buffer if any arrives).
4599
4600 If WAIT_PROC is specified, wait until something arrives from that
4601 process. The return value is true if we read some input from
4602 that process.
4603
4604 If JUST_WAIT_PROC is non-nil, handle only output from WAIT_PROC
4605 (suspending output from other processes). A negative value
4606 means don't run any timers either.
4607
4608 If WAIT_PROC is specified, then the function returns true if we
4609 received input from that process before the timeout elapsed.
4610 Otherwise, return true if we received input from any process. */
4611
4612 int
4613 wait_reading_process_output (time_limit, microsecs, read_kbd, do_display,
4614 wait_for_cell, wait_proc, just_wait_proc)
4615 int time_limit, microsecs, read_kbd, do_display;
4616 Lisp_Object wait_for_cell;
4617 struct Lisp_Process *wait_proc;
4618 int just_wait_proc;
4619 {
4620 register int channel, nfds;
4621 SELECT_TYPE Available;
4622 #ifdef NON_BLOCKING_CONNECT
4623 SELECT_TYPE Connecting;
4624 int check_connect;
4625 #endif
4626 int check_delay, no_avail;
4627 int xerrno;
4628 Lisp_Object proc;
4629 EMACS_TIME timeout, end_time;
4630 int wait_channel = -1;
4631 int got_some_input = 0;
4632 int count = SPECPDL_INDEX ();
4633
4634 FD_ZERO (&Available);
4635 #ifdef NON_BLOCKING_CONNECT
4636 FD_ZERO (&Connecting);
4637 #endif
4638
4639 /* If wait_proc is a process to watch, set wait_channel accordingly. */
4640 if (wait_proc != NULL)
4641 wait_channel = wait_proc->infd;
4642
4643 record_unwind_protect (wait_reading_process_output_unwind,
4644 make_number (waiting_for_user_input_p));
4645 waiting_for_user_input_p = read_kbd;
4646
4647 /* Since we may need to wait several times,
4648 compute the absolute time to return at. */
4649 if (time_limit || microsecs)
4650 {
4651 EMACS_GET_TIME (end_time);
4652 EMACS_SET_SECS_USECS (timeout, time_limit, microsecs);
4653 EMACS_ADD_TIME (end_time, end_time, timeout);
4654 }
4655
4656 while (1)
4657 {
4658 int timeout_reduced_for_timers = 0;
4659
4660 /* If calling from keyboard input, do not quit
4661 since we want to return C-g as an input character.
4662 Otherwise, do pending quit if requested. */
4663 if (read_kbd >= 0)
4664 QUIT;
4665 #ifdef SYNC_INPUT
4666 else
4667 process_pending_signals ();
4668 #endif
4669
4670 /* Exit now if the cell we're waiting for became non-nil. */
4671 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4672 break;
4673
4674 /* Compute time from now till when time limit is up */
4675 /* Exit if already run out */
4676 if (time_limit == -1)
4677 {
4678 /* -1 specified for timeout means
4679 gobble output available now
4680 but don't wait at all. */
4681
4682 EMACS_SET_SECS_USECS (timeout, 0, 0);
4683 }
4684 else if (time_limit || microsecs)
4685 {
4686 EMACS_GET_TIME (timeout);
4687 EMACS_SUB_TIME (timeout, end_time, timeout);
4688 if (EMACS_TIME_NEG_P (timeout))
4689 break;
4690 }
4691 else
4692 {
4693 EMACS_SET_SECS_USECS (timeout, 100000, 0);
4694 }
4695
4696 /* Normally we run timers here.
4697 But not if wait_for_cell; in those cases,
4698 the wait is supposed to be short,
4699 and those callers cannot handle running arbitrary Lisp code here. */
4700 if (NILP (wait_for_cell)
4701 && just_wait_proc >= 0)
4702 {
4703 EMACS_TIME timer_delay;
4704
4705 do
4706 {
4707 int old_timers_run = timers_run;
4708 struct buffer *old_buffer = current_buffer;
4709 Lisp_Object old_window = selected_window;
4710
4711 timer_delay = timer_check (1);
4712
4713 /* If a timer has run, this might have changed buffers
4714 an alike. Make read_key_sequence aware of that. */
4715 if (timers_run != old_timers_run
4716 && (old_buffer != current_buffer
4717 || !EQ (old_window, selected_window))
4718 && waiting_for_user_input_p == -1)
4719 record_asynch_buffer_change ();
4720
4721 if (timers_run != old_timers_run && do_display)
4722 /* We must retry, since a timer may have requeued itself
4723 and that could alter the time_delay. */
4724 redisplay_preserve_echo_area (9);
4725 else
4726 break;
4727 }
4728 while (!detect_input_pending ());
4729
4730 /* If there is unread keyboard input, also return. */
4731 if (read_kbd != 0
4732 && requeued_events_pending_p ())
4733 break;
4734
4735 if (! EMACS_TIME_NEG_P (timer_delay) && time_limit != -1)
4736 {
4737 EMACS_TIME difference;
4738 EMACS_SUB_TIME (difference, timer_delay, timeout);
4739 if (EMACS_TIME_NEG_P (difference))
4740 {
4741 timeout = timer_delay;
4742 timeout_reduced_for_timers = 1;
4743 }
4744 }
4745 /* If time_limit is -1, we are not going to wait at all. */
4746 else if (time_limit != -1)
4747 {
4748 /* This is so a breakpoint can be put here. */
4749 wait_reading_process_output_1 ();
4750 }
4751 }
4752
4753 /* Cause C-g and alarm signals to take immediate action,
4754 and cause input available signals to zero out timeout.
4755
4756 It is important that we do this before checking for process
4757 activity. If we get a SIGCHLD after the explicit checks for
4758 process activity, timeout is the only way we will know. */
4759 if (read_kbd < 0)
4760 set_waiting_for_input (&timeout);
4761
4762 /* If status of something has changed, and no input is
4763 available, notify the user of the change right away. After
4764 this explicit check, we'll let the SIGCHLD handler zap
4765 timeout to get our attention. */
4766 if (update_tick != process_tick)
4767 {
4768 SELECT_TYPE Atemp;
4769 #ifdef NON_BLOCKING_CONNECT
4770 SELECT_TYPE Ctemp;
4771 #endif
4772
4773 Atemp = input_wait_mask;
4774 IF_NON_BLOCKING_CONNECT (Ctemp = connect_wait_mask);
4775
4776 EMACS_SET_SECS_USECS (timeout, 0, 0);
4777 if ((select (max (max (max_process_desc, max_keyboard_desc),
4778 max_gpm_desc) + 1,
4779 &Atemp,
4780 #ifdef NON_BLOCKING_CONNECT
4781 (num_pending_connects > 0 ? &Ctemp : (SELECT_TYPE *)0),
4782 #else
4783 (SELECT_TYPE *)0,
4784 #endif
4785 (SELECT_TYPE *)0, &timeout)
4786 <= 0))
4787 {
4788 /* It's okay for us to do this and then continue with
4789 the loop, since timeout has already been zeroed out. */
4790 clear_waiting_for_input ();
4791 status_notify (NULL);
4792 if (do_display) redisplay_preserve_echo_area (13);
4793 }
4794 }
4795
4796 /* Don't wait for output from a non-running process. Just
4797 read whatever data has already been received. */
4798 if (wait_proc && wait_proc->raw_status_new)
4799 update_status (wait_proc);
4800 if (wait_proc
4801 && ! EQ (wait_proc->status, Qrun)
4802 && ! EQ (wait_proc->status, Qconnect))
4803 {
4804 int nread, total_nread = 0;
4805
4806 clear_waiting_for_input ();
4807 XSETPROCESS (proc, wait_proc);
4808
4809 /* Read data from the process, until we exhaust it. */
4810 while (wait_proc->infd >= 0)
4811 {
4812 nread = read_process_output (proc, wait_proc->infd);
4813
4814 if (nread == 0)
4815 break;
4816
4817 if (0 < nread)
4818 {
4819 total_nread += nread;
4820 got_some_input = 1;
4821 }
4822 #ifdef EIO
4823 else if (nread == -1 && EIO == errno)
4824 break;
4825 #endif
4826 #ifdef EAGAIN
4827 else if (nread == -1 && EAGAIN == errno)
4828 break;
4829 #endif
4830 #ifdef EWOULDBLOCK
4831 else if (nread == -1 && EWOULDBLOCK == errno)
4832 break;
4833 #endif
4834 }
4835 if (total_nread > 0 && do_display)
4836 redisplay_preserve_echo_area (10);
4837
4838 break;
4839 }
4840
4841 /* Wait till there is something to do */
4842
4843 if (wait_proc && just_wait_proc)
4844 {
4845 if (wait_proc->infd < 0) /* Terminated */
4846 break;
4847 FD_SET (wait_proc->infd, &Available);
4848 check_delay = 0;
4849 IF_NON_BLOCKING_CONNECT (check_connect = 0);
4850 }
4851 else if (!NILP (wait_for_cell))
4852 {
4853 Available = non_process_wait_mask;
4854 check_delay = 0;
4855 IF_NON_BLOCKING_CONNECT (check_connect = 0);
4856 }
4857 else
4858 {
4859 if (! read_kbd)
4860 Available = non_keyboard_wait_mask;
4861 else
4862 Available = input_wait_mask;
4863 IF_NON_BLOCKING_CONNECT (check_connect = (num_pending_connects > 0));
4864 check_delay = wait_channel >= 0 ? 0 : process_output_delay_count;
4865 }
4866
4867 /* If frame size has changed or the window is newly mapped,
4868 redisplay now, before we start to wait. There is a race
4869 condition here; if a SIGIO arrives between now and the select
4870 and indicates that a frame is trashed, the select may block
4871 displaying a trashed screen. */
4872 if (frame_garbaged && do_display)
4873 {
4874 clear_waiting_for_input ();
4875 redisplay_preserve_echo_area (11);
4876 if (read_kbd < 0)
4877 set_waiting_for_input (&timeout);
4878 }
4879
4880 no_avail = 0;
4881 if (read_kbd && detect_input_pending ())
4882 {
4883 nfds = 0;
4884 no_avail = 1;
4885 }
4886 else
4887 {
4888 #ifdef NON_BLOCKING_CONNECT
4889 if (check_connect)
4890 Connecting = connect_wait_mask;
4891 #endif
4892
4893 #ifdef ADAPTIVE_READ_BUFFERING
4894 /* Set the timeout for adaptive read buffering if any
4895 process has non-zero read_output_skip and non-zero
4896 read_output_delay, and we are not reading output for a
4897 specific wait_channel. It is not executed if
4898 Vprocess_adaptive_read_buffering is nil. */
4899 if (process_output_skip && check_delay > 0)
4900 {
4901 int usecs = EMACS_USECS (timeout);
4902 if (EMACS_SECS (timeout) > 0 || usecs > READ_OUTPUT_DELAY_MAX)
4903 usecs = READ_OUTPUT_DELAY_MAX;
4904 for (channel = 0; check_delay > 0 && channel <= max_process_desc; channel++)
4905 {
4906 proc = chan_process[channel];
4907 if (NILP (proc))
4908 continue;
4909 /* Find minimum non-zero read_output_delay among the
4910 processes with non-zero read_output_skip. */
4911 if (XPROCESS (proc)->read_output_delay > 0)
4912 {
4913 check_delay--;
4914 if (!XPROCESS (proc)->read_output_skip)
4915 continue;
4916 FD_CLR (channel, &Available);
4917 XPROCESS (proc)->read_output_skip = 0;
4918 if (XPROCESS (proc)->read_output_delay < usecs)
4919 usecs = XPROCESS (proc)->read_output_delay;
4920 }
4921 }
4922 EMACS_SET_SECS_USECS (timeout, 0, usecs);
4923 process_output_skip = 0;
4924 }
4925 #endif
4926 #ifdef HAVE_NS
4927 nfds = ns_select
4928 #else
4929 nfds = select
4930 #endif
4931 (max (max (max_process_desc, max_keyboard_desc),
4932 max_gpm_desc) + 1,
4933 &Available,
4934 #ifdef NON_BLOCKING_CONNECT
4935 (check_connect ? &Connecting : (SELECT_TYPE *)0),
4936 #else
4937 (SELECT_TYPE *)0,
4938 #endif
4939 (SELECT_TYPE *)0, &timeout);
4940 }
4941
4942 xerrno = errno;
4943
4944 /* Make C-g and alarm signals set flags again */
4945 clear_waiting_for_input ();
4946
4947 /* If we woke up due to SIGWINCH, actually change size now. */
4948 do_pending_window_change (0);
4949
4950 if (time_limit && nfds == 0 && ! timeout_reduced_for_timers)
4951 /* We wanted the full specified time, so return now. */
4952 break;
4953 if (nfds < 0)
4954 {
4955 if (xerrno == EINTR)
4956 no_avail = 1;
4957 else if (xerrno == EBADF)
4958 {
4959 #ifdef AIX
4960 /* AIX doesn't handle PTY closure the same way BSD does. On AIX,
4961 the child's closure of the pts gives the parent a SIGHUP, and
4962 the ptc file descriptor is automatically closed,
4963 yielding EBADF here or at select() call above.
4964 So, SIGHUP is ignored (see def of PTY_TTY_NAME_SPRINTF
4965 in m/ibmrt-aix.h), and here we just ignore the select error.
4966 Cleanup occurs c/o status_notify after SIGCLD. */
4967 no_avail = 1; /* Cannot depend on values returned */
4968 #else
4969 abort ();
4970 #endif
4971 }
4972 else
4973 error ("select error: %s", emacs_strerror (xerrno));
4974 }
4975
4976 if (no_avail)
4977 {
4978 FD_ZERO (&Available);
4979 IF_NON_BLOCKING_CONNECT (check_connect = 0);
4980 }
4981
4982 #if 0 /* When polling is used, interrupt_input is 0,
4983 so get_input_pending should read the input.
4984 So this should not be needed. */
4985 /* If we are using polling for input,
4986 and we see input available, make it get read now.
4987 Otherwise it might not actually get read for a second.
4988 And on hpux, since we turn off polling in wait_reading_process_output,
4989 it might never get read at all if we don't spend much time
4990 outside of wait_reading_process_output. */
4991 if (read_kbd && interrupt_input
4992 && keyboard_bit_set (&Available)
4993 && input_polling_used ())
4994 kill (getpid (), SIGALRM);
4995 #endif
4996
4997 /* Check for keyboard input */
4998 /* If there is any, return immediately
4999 to give it higher priority than subprocesses */
5000
5001 if (read_kbd != 0)
5002 {
5003 int old_timers_run = timers_run;
5004 struct buffer *old_buffer = current_buffer;
5005 Lisp_Object old_window = selected_window;
5006 int leave = 0;
5007
5008 if (detect_input_pending_run_timers (do_display))
5009 {
5010 swallow_events (do_display);
5011 if (detect_input_pending_run_timers (do_display))
5012 leave = 1;
5013 }
5014
5015 /* If a timer has run, this might have changed buffers
5016 an alike. Make read_key_sequence aware of that. */
5017 if (timers_run != old_timers_run
5018 && waiting_for_user_input_p == -1
5019 && (old_buffer != current_buffer
5020 || !EQ (old_window, selected_window)))
5021 record_asynch_buffer_change ();
5022
5023 if (leave)
5024 break;
5025 }
5026
5027 /* If there is unread keyboard input, also return. */
5028 if (read_kbd != 0
5029 && requeued_events_pending_p ())
5030 break;
5031
5032 /* If we are not checking for keyboard input now,
5033 do process events (but don't run any timers).
5034 This is so that X events will be processed.
5035 Otherwise they may have to wait until polling takes place.
5036 That would causes delays in pasting selections, for example.
5037
5038 (We used to do this only if wait_for_cell.) */
5039 if (read_kbd == 0 && detect_input_pending ())
5040 {
5041 swallow_events (do_display);
5042 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
5043 if (detect_input_pending ())
5044 break;
5045 #endif
5046 }
5047
5048 /* Exit now if the cell we're waiting for became non-nil. */
5049 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
5050 break;
5051
5052 #ifdef SIGIO
5053 /* If we think we have keyboard input waiting, but didn't get SIGIO,
5054 go read it. This can happen with X on BSD after logging out.
5055 In that case, there really is no input and no SIGIO,
5056 but select says there is input. */
5057
5058 if (read_kbd && interrupt_input
5059 && keyboard_bit_set (&Available) && ! noninteractive)
5060 kill (getpid (), SIGIO);
5061 #endif
5062
5063 if (! wait_proc)
5064 got_some_input |= nfds > 0;
5065
5066 /* If checking input just got us a size-change event from X,
5067 obey it now if we should. */
5068 if (read_kbd || ! NILP (wait_for_cell))
5069 do_pending_window_change (0);
5070
5071 /* Check for data from a process. */
5072 if (no_avail || nfds == 0)
5073 continue;
5074
5075 /* Really FIRST_PROC_DESC should be 0 on Unix,
5076 but this is safer in the short run. */
5077 for (channel = 0; channel <= max_process_desc; channel++)
5078 {
5079 if (FD_ISSET (channel, &Available)
5080 && FD_ISSET (channel, &non_keyboard_wait_mask))
5081 {
5082 int nread;
5083
5084 /* If waiting for this channel, arrange to return as
5085 soon as no more input to be processed. No more
5086 waiting. */
5087 if (wait_channel == channel)
5088 {
5089 wait_channel = -1;
5090 time_limit = -1;
5091 got_some_input = 1;
5092 }
5093 proc = chan_process[channel];
5094 if (NILP (proc))
5095 continue;
5096
5097 /* If this is a server stream socket, accept connection. */
5098 if (EQ (XPROCESS (proc)->status, Qlisten))
5099 {
5100 server_accept_connection (proc, channel);
5101 continue;
5102 }
5103
5104 /* Read data from the process, starting with our
5105 buffered-ahead character if we have one. */
5106
5107 nread = read_process_output (proc, channel);
5108 if (nread > 0)
5109 {
5110 /* Since read_process_output can run a filter,
5111 which can call accept-process-output,
5112 don't try to read from any other processes
5113 before doing the select again. */
5114 FD_ZERO (&Available);
5115
5116 if (do_display)
5117 redisplay_preserve_echo_area (12);
5118 }
5119 #ifdef EWOULDBLOCK
5120 else if (nread == -1 && errno == EWOULDBLOCK)
5121 ;
5122 #endif
5123 /* ISC 4.1 defines both EWOULDBLOCK and O_NONBLOCK,
5124 and Emacs uses O_NONBLOCK, so what we get is EAGAIN. */
5125 #ifdef O_NONBLOCK
5126 else if (nread == -1 && errno == EAGAIN)
5127 ;
5128 #else
5129 #ifdef O_NDELAY
5130 else if (nread == -1 && errno == EAGAIN)
5131 ;
5132 /* Note that we cannot distinguish between no input
5133 available now and a closed pipe.
5134 With luck, a closed pipe will be accompanied by
5135 subprocess termination and SIGCHLD. */
5136 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
5137 ;
5138 #endif /* O_NDELAY */
5139 #endif /* O_NONBLOCK */
5140 #ifdef HAVE_PTYS
5141 /* On some OSs with ptys, when the process on one end of
5142 a pty exits, the other end gets an error reading with
5143 errno = EIO instead of getting an EOF (0 bytes read).
5144 Therefore, if we get an error reading and errno =
5145 EIO, just continue, because the child process has
5146 exited and should clean itself up soon (e.g. when we
5147 get a SIGCHLD).
5148
5149 However, it has been known to happen that the SIGCHLD
5150 got lost. So raise the signal again just in case.
5151 It can't hurt. */
5152 else if (nread == -1 && errno == EIO)
5153 {
5154 /* Clear the descriptor now, so we only raise the
5155 signal once. Don't do this if `process' is only
5156 a pty. */
5157 if (XPROCESS (proc)->pid != -2)
5158 {
5159 FD_CLR (channel, &input_wait_mask);
5160 FD_CLR (channel, &non_keyboard_wait_mask);
5161
5162 kill (getpid (), SIGCHLD);
5163 }
5164 }
5165 #endif /* HAVE_PTYS */
5166 /* If we can detect process termination, don't consider the process
5167 gone just because its pipe is closed. */
5168 #ifdef SIGCHLD
5169 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
5170 ;
5171 #endif
5172 else
5173 {
5174 /* Preserve status of processes already terminated. */
5175 XPROCESS (proc)->tick = ++process_tick;
5176 deactivate_process (proc);
5177 if (XPROCESS (proc)->raw_status_new)
5178 update_status (XPROCESS (proc));
5179 if (EQ (XPROCESS (proc)->status, Qrun))
5180 XPROCESS (proc)->status
5181 = Fcons (Qexit, Fcons (make_number (256), Qnil));
5182 }
5183 }
5184 #ifdef NON_BLOCKING_CONNECT
5185 if (check_connect && FD_ISSET (channel, &Connecting)
5186 && FD_ISSET (channel, &connect_wait_mask))
5187 {
5188 struct Lisp_Process *p;
5189
5190 FD_CLR (channel, &connect_wait_mask);
5191 if (--num_pending_connects < 0)
5192 abort ();
5193
5194 proc = chan_process[channel];
5195 if (NILP (proc))
5196 continue;
5197
5198 p = XPROCESS (proc);
5199
5200 #ifdef GNU_LINUX
5201 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
5202 So only use it on systems where it is known to work. */
5203 {
5204 int xlen = sizeof(xerrno);
5205 if (getsockopt(channel, SOL_SOCKET, SO_ERROR, &xerrno, &xlen))
5206 xerrno = errno;
5207 }
5208 #else
5209 {
5210 struct sockaddr pname;
5211 int pnamelen = sizeof(pname);
5212
5213 /* If connection failed, getpeername will fail. */
5214 xerrno = 0;
5215 if (getpeername(channel, &pname, &pnamelen) < 0)
5216 {
5217 /* Obtain connect failure code through error slippage. */
5218 char dummy;
5219 xerrno = errno;
5220 if (errno == ENOTCONN && read(channel, &dummy, 1) < 0)
5221 xerrno = errno;
5222 }
5223 }
5224 #endif
5225 if (xerrno)
5226 {
5227 p->tick = ++process_tick;
5228 p->status = Fcons (Qfailed, Fcons (make_number (xerrno), Qnil));
5229 deactivate_process (proc);
5230 }
5231 else
5232 {
5233 p->status = Qrun;
5234 /* Execute the sentinel here. If we had relied on
5235 status_notify to do it later, it will read input
5236 from the process before calling the sentinel. */
5237 exec_sentinel (proc, build_string ("open\n"));
5238 if (!EQ (p->filter, Qt) && !EQ (p->command, Qt))
5239 {
5240 FD_SET (p->infd, &input_wait_mask);
5241 FD_SET (p->infd, &non_keyboard_wait_mask);
5242 }
5243 }
5244 }
5245 #endif /* NON_BLOCKING_CONNECT */
5246 } /* end for each file descriptor */
5247 } /* end while exit conditions not met */
5248
5249 unbind_to (count, Qnil);
5250
5251 /* If calling from keyboard input, do not quit
5252 since we want to return C-g as an input character.
5253 Otherwise, do pending quit if requested. */
5254 if (read_kbd >= 0)
5255 {
5256 /* Prevent input_pending from remaining set if we quit. */
5257 clear_input_pending ();
5258 QUIT;
5259 }
5260
5261 return got_some_input;
5262 }
5263 \f
5264 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
5265
5266 static Lisp_Object
5267 read_process_output_call (fun_and_args)
5268 Lisp_Object fun_and_args;
5269 {
5270 return apply1 (XCAR (fun_and_args), XCDR (fun_and_args));
5271 }
5272
5273 static Lisp_Object
5274 read_process_output_error_handler (error)
5275 Lisp_Object error;
5276 {
5277 cmd_error_internal (error, "error in process filter: ");
5278 Vinhibit_quit = Qt;
5279 update_echo_area ();
5280 Fsleep_for (make_number (2), Qnil);
5281 return Qt;
5282 }
5283
5284 /* Read pending output from the process channel,
5285 starting with our buffered-ahead character if we have one.
5286 Yield number of decoded characters read.
5287
5288 This function reads at most 4096 characters.
5289 If you want to read all available subprocess output,
5290 you must call it repeatedly until it returns zero.
5291
5292 The characters read are decoded according to PROC's coding-system
5293 for decoding. */
5294
5295 static int
5296 read_process_output (proc, channel)
5297 Lisp_Object proc;
5298 register int channel;
5299 {
5300 register int nbytes;
5301 char *chars;
5302 register Lisp_Object outstream;
5303 register struct Lisp_Process *p = XPROCESS (proc);
5304 register int opoint;
5305 struct coding_system *coding = proc_decode_coding_system[channel];
5306 int carryover = p->decoding_carryover;
5307 int readmax = 4096;
5308
5309 chars = (char *) alloca (carryover + readmax);
5310 if (carryover)
5311 /* See the comment above. */
5312 bcopy (SDATA (p->decoding_buf), chars, carryover);
5313
5314 #ifdef DATAGRAM_SOCKETS
5315 /* We have a working select, so proc_buffered_char is always -1. */
5316 if (DATAGRAM_CHAN_P (channel))
5317 {
5318 int len = datagram_address[channel].len;
5319 nbytes = recvfrom (channel, chars + carryover, readmax,
5320 0, datagram_address[channel].sa, &len);
5321 }
5322 else
5323 #endif
5324 if (proc_buffered_char[channel] < 0)
5325 {
5326 nbytes = emacs_read (channel, chars + carryover, readmax);
5327 #ifdef ADAPTIVE_READ_BUFFERING
5328 if (nbytes > 0 && p->adaptive_read_buffering)
5329 {
5330 int delay = p->read_output_delay;
5331 if (nbytes < 256)
5332 {
5333 if (delay < READ_OUTPUT_DELAY_MAX_MAX)
5334 {
5335 if (delay == 0)
5336 process_output_delay_count++;
5337 delay += READ_OUTPUT_DELAY_INCREMENT * 2;
5338 }
5339 }
5340 else if (delay > 0 && (nbytes == readmax))
5341 {
5342 delay -= READ_OUTPUT_DELAY_INCREMENT;
5343 if (delay == 0)
5344 process_output_delay_count--;
5345 }
5346 p->read_output_delay = delay;
5347 if (delay)
5348 {
5349 p->read_output_skip = 1;
5350 process_output_skip = 1;
5351 }
5352 }
5353 #endif
5354 }
5355 else
5356 {
5357 chars[carryover] = proc_buffered_char[channel];
5358 proc_buffered_char[channel] = -1;
5359 nbytes = emacs_read (channel, chars + carryover + 1, readmax - 1);
5360 if (nbytes < 0)
5361 nbytes = 1;
5362 else
5363 nbytes = nbytes + 1;
5364 }
5365
5366 p->decoding_carryover = 0;
5367
5368 /* At this point, NBYTES holds number of bytes just received
5369 (including the one in proc_buffered_char[channel]). */
5370 if (nbytes <= 0)
5371 {
5372 if (nbytes < 0 || coding->mode & CODING_MODE_LAST_BLOCK)
5373 return nbytes;
5374 coding->mode |= CODING_MODE_LAST_BLOCK;
5375 }
5376
5377 /* Now set NBYTES how many bytes we must decode. */
5378 nbytes += carryover;
5379
5380 /* Read and dispose of the process output. */
5381 outstream = p->filter;
5382 if (!NILP (outstream))
5383 {
5384 /* We inhibit quit here instead of just catching it so that
5385 hitting ^G when a filter happens to be running won't screw
5386 it up. */
5387 int count = SPECPDL_INDEX ();
5388 Lisp_Object odeactivate;
5389 Lisp_Object obuffer, okeymap;
5390 Lisp_Object text;
5391 int outer_running_asynch_code = running_asynch_code;
5392 int waiting = waiting_for_user_input_p;
5393
5394 /* No need to gcpro these, because all we do with them later
5395 is test them for EQness, and none of them should be a string. */
5396 odeactivate = Vdeactivate_mark;
5397 XSETBUFFER (obuffer, current_buffer);
5398 okeymap = current_buffer->keymap;
5399
5400 specbind (Qinhibit_quit, Qt);
5401 specbind (Qlast_nonmenu_event, Qt);
5402
5403 /* In case we get recursively called,
5404 and we already saved the match data nonrecursively,
5405 save the same match data in safely recursive fashion. */
5406 if (outer_running_asynch_code)
5407 {
5408 Lisp_Object tem;
5409 /* Don't clobber the CURRENT match data, either! */
5410 tem = Fmatch_data (Qnil, Qnil, Qnil);
5411 restore_search_regs ();
5412 record_unwind_save_match_data ();
5413 Fset_match_data (tem, Qt);
5414 }
5415
5416 /* For speed, if a search happens within this code,
5417 save the match data in a special nonrecursive fashion. */
5418 running_asynch_code = 1;
5419
5420 decode_coding_c_string (coding, chars, nbytes, Qt);
5421 text = coding->dst_object;
5422 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5423 /* A new coding system might be found. */
5424 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5425 {
5426 p->decode_coding_system = Vlast_coding_system_used;
5427
5428 /* Don't call setup_coding_system for
5429 proc_decode_coding_system[channel] here. It is done in
5430 detect_coding called via decode_coding above. */
5431
5432 /* If a coding system for encoding is not yet decided, we set
5433 it as the same as coding-system for decoding.
5434
5435 But, before doing that we must check if
5436 proc_encode_coding_system[p->outfd] surely points to a
5437 valid memory because p->outfd will be changed once EOF is
5438 sent to the process. */
5439 if (NILP (p->encode_coding_system)
5440 && proc_encode_coding_system[p->outfd])
5441 {
5442 p->encode_coding_system
5443 = coding_inherit_eol_type (Vlast_coding_system_used, Qnil);
5444 setup_coding_system (p->encode_coding_system,
5445 proc_encode_coding_system[p->outfd]);
5446 }
5447 }
5448
5449 if (coding->carryover_bytes > 0)
5450 {
5451 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5452 p->decoding_buf = make_uninit_string (coding->carryover_bytes);
5453 bcopy (coding->carryover, SDATA (p->decoding_buf),
5454 coding->carryover_bytes);
5455 p->decoding_carryover = coding->carryover_bytes;
5456 }
5457 if (SBYTES (text) > 0)
5458 internal_condition_case_1 (read_process_output_call,
5459 Fcons (outstream,
5460 Fcons (proc, Fcons (text, Qnil))),
5461 !NILP (Vdebug_on_error) ? Qnil : Qerror,
5462 read_process_output_error_handler);
5463
5464 /* If we saved the match data nonrecursively, restore it now. */
5465 restore_search_regs ();
5466 running_asynch_code = outer_running_asynch_code;
5467
5468 /* Handling the process output should not deactivate the mark. */
5469 Vdeactivate_mark = odeactivate;
5470
5471 /* Restore waiting_for_user_input_p as it was
5472 when we were called, in case the filter clobbered it. */
5473 waiting_for_user_input_p = waiting;
5474
5475 #if 0 /* Call record_asynch_buffer_change unconditionally,
5476 because we might have changed minor modes or other things
5477 that affect key bindings. */
5478 if (! EQ (Fcurrent_buffer (), obuffer)
5479 || ! EQ (current_buffer->keymap, okeymap))
5480 #endif
5481 /* But do it only if the caller is actually going to read events.
5482 Otherwise there's no need to make him wake up, and it could
5483 cause trouble (for example it would make sit_for return). */
5484 if (waiting_for_user_input_p == -1)
5485 record_asynch_buffer_change ();
5486
5487 unbind_to (count, Qnil);
5488 return nbytes;
5489 }
5490
5491 /* If no filter, write into buffer if it isn't dead. */
5492 if (!NILP (p->buffer) && !NILP (XBUFFER (p->buffer)->name))
5493 {
5494 Lisp_Object old_read_only;
5495 int old_begv, old_zv;
5496 int old_begv_byte, old_zv_byte;
5497 Lisp_Object odeactivate;
5498 int before, before_byte;
5499 int opoint_byte;
5500 Lisp_Object text;
5501 struct buffer *b;
5502 int count = SPECPDL_INDEX ();
5503
5504 odeactivate = Vdeactivate_mark;
5505
5506 record_unwind_protect (Fset_buffer, Fcurrent_buffer ());
5507 Fset_buffer (p->buffer);
5508 opoint = PT;
5509 opoint_byte = PT_BYTE;
5510 old_read_only = current_buffer->read_only;
5511 old_begv = BEGV;
5512 old_zv = ZV;
5513 old_begv_byte = BEGV_BYTE;
5514 old_zv_byte = ZV_BYTE;
5515
5516 current_buffer->read_only = Qnil;
5517
5518 /* Insert new output into buffer
5519 at the current end-of-output marker,
5520 thus preserving logical ordering of input and output. */
5521 if (XMARKER (p->mark)->buffer)
5522 SET_PT_BOTH (clip_to_bounds (BEGV, marker_position (p->mark), ZV),
5523 clip_to_bounds (BEGV_BYTE, marker_byte_position (p->mark),
5524 ZV_BYTE));
5525 else
5526 SET_PT_BOTH (ZV, ZV_BYTE);
5527 before = PT;
5528 before_byte = PT_BYTE;
5529
5530 /* If the output marker is outside of the visible region, save
5531 the restriction and widen. */
5532 if (! (BEGV <= PT && PT <= ZV))
5533 Fwiden ();
5534
5535 decode_coding_c_string (coding, chars, nbytes, Qt);
5536 text = coding->dst_object;
5537 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5538 /* A new coding system might be found. See the comment in the
5539 similar code in the previous `if' block. */
5540 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5541 {
5542 p->decode_coding_system = Vlast_coding_system_used;
5543 if (NILP (p->encode_coding_system)
5544 && proc_encode_coding_system[p->outfd])
5545 {
5546 p->encode_coding_system
5547 = coding_inherit_eol_type (Vlast_coding_system_used, Qnil);
5548 setup_coding_system (p->encode_coding_system,
5549 proc_encode_coding_system[p->outfd]);
5550 }
5551 }
5552 if (coding->carryover_bytes > 0)
5553 {
5554 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5555 p->decoding_buf = make_uninit_string (coding->carryover_bytes);
5556 bcopy (coding->carryover, SDATA (p->decoding_buf),
5557 coding->carryover_bytes);
5558 p->decoding_carryover = coding->carryover_bytes;
5559 }
5560 /* Adjust the multibyteness of TEXT to that of the buffer. */
5561 if (NILP (current_buffer->enable_multibyte_characters)
5562 != ! STRING_MULTIBYTE (text))
5563 text = (STRING_MULTIBYTE (text)
5564 ? Fstring_as_unibyte (text)
5565 : Fstring_to_multibyte (text));
5566 /* Insert before markers in case we are inserting where
5567 the buffer's mark is, and the user's next command is Meta-y. */
5568 insert_from_string_before_markers (text, 0, 0,
5569 SCHARS (text), SBYTES (text), 0);
5570
5571 /* Make sure the process marker's position is valid when the
5572 process buffer is changed in the signal_after_change above.
5573 W3 is known to do that. */
5574 if (BUFFERP (p->buffer)
5575 && (b = XBUFFER (p->buffer), b != current_buffer))
5576 set_marker_both (p->mark, p->buffer, BUF_PT (b), BUF_PT_BYTE (b));
5577 else
5578 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
5579
5580 update_mode_lines++;
5581
5582 /* Make sure opoint and the old restrictions
5583 float ahead of any new text just as point would. */
5584 if (opoint >= before)
5585 {
5586 opoint += PT - before;
5587 opoint_byte += PT_BYTE - before_byte;
5588 }
5589 if (old_begv > before)
5590 {
5591 old_begv += PT - before;
5592 old_begv_byte += PT_BYTE - before_byte;
5593 }
5594 if (old_zv >= before)
5595 {
5596 old_zv += PT - before;
5597 old_zv_byte += PT_BYTE - before_byte;
5598 }
5599
5600 /* If the restriction isn't what it should be, set it. */
5601 if (old_begv != BEGV || old_zv != ZV)
5602 Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
5603
5604 /* Handling the process output should not deactivate the mark. */
5605 Vdeactivate_mark = odeactivate;
5606
5607 current_buffer->read_only = old_read_only;
5608 SET_PT_BOTH (opoint, opoint_byte);
5609 unbind_to (count, Qnil);
5610 }
5611 return nbytes;
5612 }
5613
5614 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p, Swaiting_for_user_input_p,
5615 0, 0, 0,
5616 doc: /* Returns non-nil if Emacs is waiting for input from the user.
5617 This is intended for use by asynchronous process output filters and sentinels. */)
5618 ()
5619 {
5620 return (waiting_for_user_input_p ? Qt : Qnil);
5621 }
5622 \f
5623 /* Sending data to subprocess */
5624
5625 jmp_buf send_process_frame;
5626 Lisp_Object process_sent_to;
5627
5628 SIGTYPE
5629 send_process_trap ()
5630 {
5631 SIGNAL_THREAD_CHECK (SIGPIPE);
5632 sigunblock (sigmask (SIGPIPE));
5633 longjmp (send_process_frame, 1);
5634 }
5635
5636 /* Send some data to process PROC.
5637 BUF is the beginning of the data; LEN is the number of characters.
5638 OBJECT is the Lisp object that the data comes from. If OBJECT is
5639 nil or t, it means that the data comes from C string.
5640
5641 If OBJECT is not nil, the data is encoded by PROC's coding-system
5642 for encoding before it is sent.
5643
5644 This function can evaluate Lisp code and can garbage collect. */
5645
5646 static void
5647 send_process (proc, buf, len, object)
5648 volatile Lisp_Object proc;
5649 unsigned char *volatile buf;
5650 volatile int len;
5651 volatile Lisp_Object object;
5652 {
5653 /* Use volatile to protect variables from being clobbered by longjmp. */
5654 struct Lisp_Process *p = XPROCESS (proc);
5655 int rv;
5656 struct coding_system *coding;
5657 struct gcpro gcpro1;
5658 SIGTYPE (*volatile old_sigpipe) ();
5659
5660 GCPRO1 (object);
5661
5662 if (p->raw_status_new)
5663 update_status (p);
5664 if (! EQ (p->status, Qrun))
5665 error ("Process %s not running", SDATA (p->name));
5666 if (p->outfd < 0)
5667 error ("Output file descriptor of %s is closed", SDATA (p->name));
5668
5669 coding = proc_encode_coding_system[p->outfd];
5670 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5671
5672 if ((STRINGP (object) && STRING_MULTIBYTE (object))
5673 || (BUFFERP (object)
5674 && !NILP (XBUFFER (object)->enable_multibyte_characters))
5675 || EQ (object, Qt))
5676 {
5677 if (!EQ (Vlast_coding_system_used, p->encode_coding_system))
5678 /* The coding system for encoding was changed to raw-text
5679 because we sent a unibyte text previously. Now we are
5680 sending a multibyte text, thus we must encode it by the
5681 original coding system specified for the current process. */
5682 setup_coding_system (p->encode_coding_system, coding);
5683 coding->src_multibyte = 1;
5684 }
5685 else
5686 {
5687 /* For sending a unibyte text, character code conversion should
5688 not take place but EOL conversion should. So, setup raw-text
5689 or one of the subsidiary if we have not yet done it. */
5690 if (CODING_REQUIRE_ENCODING (coding))
5691 {
5692 if (CODING_REQUIRE_FLUSHING (coding))
5693 {
5694 /* But, before changing the coding, we must flush out data. */
5695 coding->mode |= CODING_MODE_LAST_BLOCK;
5696 send_process (proc, "", 0, Qt);
5697 coding->mode &= CODING_MODE_LAST_BLOCK;
5698 }
5699 setup_coding_system (raw_text_coding_system
5700 (Vlast_coding_system_used),
5701 coding);
5702 coding->src_multibyte = 0;
5703 }
5704 }
5705 coding->dst_multibyte = 0;
5706
5707 if (CODING_REQUIRE_ENCODING (coding))
5708 {
5709 coding->dst_object = Qt;
5710 if (BUFFERP (object))
5711 {
5712 int from_byte, from, to;
5713 int save_pt, save_pt_byte;
5714 struct buffer *cur = current_buffer;
5715
5716 set_buffer_internal (XBUFFER (object));
5717 save_pt = PT, save_pt_byte = PT_BYTE;
5718
5719 from_byte = PTR_BYTE_POS (buf);
5720 from = BYTE_TO_CHAR (from_byte);
5721 to = BYTE_TO_CHAR (from_byte + len);
5722 TEMP_SET_PT_BOTH (from, from_byte);
5723 encode_coding_object (coding, object, from, from_byte,
5724 to, from_byte + len, Qt);
5725 TEMP_SET_PT_BOTH (save_pt, save_pt_byte);
5726 set_buffer_internal (cur);
5727 }
5728 else if (STRINGP (object))
5729 {
5730 encode_coding_object (coding, object, 0, 0, SCHARS (object),
5731 SBYTES (object), Qt);
5732 }
5733 else
5734 {
5735 coding->dst_object = make_unibyte_string (buf, len);
5736 coding->produced = len;
5737 }
5738
5739 len = coding->produced;
5740 object = coding->dst_object;
5741 buf = SDATA (object);
5742 }
5743
5744 if (pty_max_bytes == 0)
5745 {
5746 #if defined (HAVE_FPATHCONF) && defined (_PC_MAX_CANON)
5747 pty_max_bytes = fpathconf (p->outfd, _PC_MAX_CANON);
5748 if (pty_max_bytes < 0)
5749 pty_max_bytes = 250;
5750 #else
5751 pty_max_bytes = 250;
5752 #endif
5753 /* Deduct one, to leave space for the eof. */
5754 pty_max_bytes--;
5755 }
5756
5757 /* 2000-09-21: Emacs 20.7, sparc-sun-solaris-2.6, GCC 2.95.2,
5758 CFLAGS="-g -O": The value of the parameter `proc' is clobbered
5759 when returning with longjmp despite being declared volatile. */
5760 if (!setjmp (send_process_frame))
5761 {
5762 process_sent_to = proc;
5763 while (len > 0)
5764 {
5765 int this = len;
5766
5767 /* Decide how much data we can send in one batch.
5768 Long lines need to be split into multiple batches. */
5769 if (p->pty_flag)
5770 {
5771 /* Starting this at zero is always correct when not the first
5772 iteration because the previous iteration ended by sending C-d.
5773 It may not be correct for the first iteration
5774 if a partial line was sent in a separate send_process call.
5775 If that proves worth handling, we need to save linepos
5776 in the process object. */
5777 int linepos = 0;
5778 unsigned char *ptr = (unsigned char *) buf;
5779 unsigned char *end = (unsigned char *) buf + len;
5780
5781 /* Scan through this text for a line that is too long. */
5782 while (ptr != end && linepos < pty_max_bytes)
5783 {
5784 if (*ptr == '\n')
5785 linepos = 0;
5786 else
5787 linepos++;
5788 ptr++;
5789 }
5790 /* If we found one, break the line there
5791 and put in a C-d to force the buffer through. */
5792 this = ptr - buf;
5793 }
5794
5795 /* Send this batch, using one or more write calls. */
5796 while (this > 0)
5797 {
5798 int outfd = p->outfd;
5799 old_sigpipe = (SIGTYPE (*) ()) signal (SIGPIPE, send_process_trap);
5800 #ifdef DATAGRAM_SOCKETS
5801 if (DATAGRAM_CHAN_P (outfd))
5802 {
5803 rv = sendto (outfd, (char *) buf, this,
5804 0, datagram_address[outfd].sa,
5805 datagram_address[outfd].len);
5806 if (rv < 0 && errno == EMSGSIZE)
5807 {
5808 signal (SIGPIPE, old_sigpipe);
5809 report_file_error ("sending datagram",
5810 Fcons (proc, Qnil));
5811 }
5812 }
5813 else
5814 #endif
5815 {
5816 rv = emacs_write (outfd, (char *) buf, this);
5817 #ifdef ADAPTIVE_READ_BUFFERING
5818 if (p->read_output_delay > 0
5819 && p->adaptive_read_buffering == 1)
5820 {
5821 p->read_output_delay = 0;
5822 process_output_delay_count--;
5823 p->read_output_skip = 0;
5824 }
5825 #endif
5826 }
5827 signal (SIGPIPE, old_sigpipe);
5828
5829 if (rv < 0)
5830 {
5831 if (0
5832 #ifdef EWOULDBLOCK
5833 || errno == EWOULDBLOCK
5834 #endif
5835 #ifdef EAGAIN
5836 || errno == EAGAIN
5837 #endif
5838 )
5839 /* Buffer is full. Wait, accepting input;
5840 that may allow the program
5841 to finish doing output and read more. */
5842 {
5843 int offset = 0;
5844
5845 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
5846 /* A gross hack to work around a bug in FreeBSD.
5847 In the following sequence, read(2) returns
5848 bogus data:
5849
5850 write(2) 1022 bytes
5851 write(2) 954 bytes, get EAGAIN
5852 read(2) 1024 bytes in process_read_output
5853 read(2) 11 bytes in process_read_output
5854
5855 That is, read(2) returns more bytes than have
5856 ever been written successfully. The 1033 bytes
5857 read are the 1022 bytes written successfully
5858 after processing (for example with CRs added if
5859 the terminal is set up that way which it is
5860 here). The same bytes will be seen again in a
5861 later read(2), without the CRs. */
5862
5863 if (errno == EAGAIN)
5864 {
5865 int flags = FWRITE;
5866 ioctl (p->outfd, TIOCFLUSH, &flags);
5867 }
5868 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
5869
5870 /* Running filters might relocate buffers or strings.
5871 Arrange to relocate BUF. */
5872 if (BUFFERP (object))
5873 offset = BUF_PTR_BYTE_POS (XBUFFER (object), buf);
5874 else if (STRINGP (object))
5875 offset = buf - SDATA (object);
5876
5877 #ifdef EMACS_HAS_USECS
5878 wait_reading_process_output (0, 20000, 0, 0, Qnil, NULL, 0);
5879 #else
5880 wait_reading_process_output (1, 0, 0, 0, Qnil, NULL, 0);
5881 #endif
5882
5883 if (BUFFERP (object))
5884 buf = BUF_BYTE_ADDRESS (XBUFFER (object), offset);
5885 else if (STRINGP (object))
5886 buf = offset + SDATA (object);
5887
5888 rv = 0;
5889 }
5890 else
5891 /* This is a real error. */
5892 report_file_error ("writing to process", Fcons (proc, Qnil));
5893 }
5894 buf += rv;
5895 len -= rv;
5896 this -= rv;
5897 }
5898
5899 /* If we sent just part of the string, put in an EOF (C-d)
5900 to force it through, before we send the rest. */
5901 if (len > 0)
5902 Fprocess_send_eof (proc);
5903 }
5904 }
5905 else
5906 {
5907 signal (SIGPIPE, old_sigpipe);
5908 proc = process_sent_to;
5909 p = XPROCESS (proc);
5910 p->raw_status_new = 0;
5911 p->status = Fcons (Qexit, Fcons (make_number (256), Qnil));
5912 p->tick = ++process_tick;
5913 deactivate_process (proc);
5914 error ("SIGPIPE raised on process %s; closed it", SDATA (p->name));
5915 }
5916
5917 UNGCPRO;
5918 }
5919
5920 DEFUN ("process-send-region", Fprocess_send_region, Sprocess_send_region,
5921 3, 3, 0,
5922 doc: /* Send current contents of region as input to PROCESS.
5923 PROCESS may be a process, a buffer, the name of a process or buffer, or
5924 nil, indicating the current buffer's process.
5925 Called from program, takes three arguments, PROCESS, START and END.
5926 If the region is more than 500 characters long,
5927 it is sent in several bunches. This may happen even for shorter regions.
5928 Output from processes can arrive in between bunches. */)
5929 (process, start, end)
5930 Lisp_Object process, start, end;
5931 {
5932 Lisp_Object proc;
5933 int start1, end1;
5934
5935 proc = get_process (process);
5936 validate_region (&start, &end);
5937
5938 if (XINT (start) < GPT && XINT (end) > GPT)
5939 move_gap (XINT (start));
5940
5941 start1 = CHAR_TO_BYTE (XINT (start));
5942 end1 = CHAR_TO_BYTE (XINT (end));
5943 send_process (proc, BYTE_POS_ADDR (start1), end1 - start1,
5944 Fcurrent_buffer ());
5945
5946 return Qnil;
5947 }
5948
5949 DEFUN ("process-send-string", Fprocess_send_string, Sprocess_send_string,
5950 2, 2, 0,
5951 doc: /* Send PROCESS the contents of STRING as input.
5952 PROCESS may be a process, a buffer, the name of a process or buffer, or
5953 nil, indicating the current buffer's process.
5954 If STRING is more than 500 characters long,
5955 it is sent in several bunches. This may happen even for shorter strings.
5956 Output from processes can arrive in between bunches. */)
5957 (process, string)
5958 Lisp_Object process, string;
5959 {
5960 Lisp_Object proc;
5961 CHECK_STRING (string);
5962 proc = get_process (process);
5963 send_process (proc, SDATA (string),
5964 SBYTES (string), string);
5965 return Qnil;
5966 }
5967 \f
5968 /* Return the foreground process group for the tty/pty that
5969 the process P uses. */
5970 static int
5971 emacs_get_tty_pgrp (p)
5972 struct Lisp_Process *p;
5973 {
5974 int gid = -1;
5975
5976 #ifdef TIOCGPGRP
5977 if (ioctl (p->infd, TIOCGPGRP, &gid) == -1 && ! NILP (p->tty_name))
5978 {
5979 int fd;
5980 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
5981 master side. Try the slave side. */
5982 fd = emacs_open (SDATA (p->tty_name), O_RDONLY, 0);
5983
5984 if (fd != -1)
5985 {
5986 ioctl (fd, TIOCGPGRP, &gid);
5987 emacs_close (fd);
5988 }
5989 }
5990 #endif /* defined (TIOCGPGRP ) */
5991
5992 return gid;
5993 }
5994
5995 DEFUN ("process-running-child-p", Fprocess_running_child_p,
5996 Sprocess_running_child_p, 0, 1, 0,
5997 doc: /* Return t if PROCESS has given the terminal to a child.
5998 If the operating system does not make it possible to find out,
5999 return t unconditionally. */)
6000 (process)
6001 Lisp_Object process;
6002 {
6003 /* Initialize in case ioctl doesn't exist or gives an error,
6004 in a way that will cause returning t. */
6005 int gid;
6006 Lisp_Object proc;
6007 struct Lisp_Process *p;
6008
6009 proc = get_process (process);
6010 p = XPROCESS (proc);
6011
6012 if (!EQ (p->type, Qreal))
6013 error ("Process %s is not a subprocess",
6014 SDATA (p->name));
6015 if (p->infd < 0)
6016 error ("Process %s is not active",
6017 SDATA (p->name));
6018
6019 gid = emacs_get_tty_pgrp (p);
6020
6021 if (gid == p->pid)
6022 return Qnil;
6023 return Qt;
6024 }
6025 \f
6026 /* send a signal number SIGNO to PROCESS.
6027 If CURRENT_GROUP is t, that means send to the process group
6028 that currently owns the terminal being used to communicate with PROCESS.
6029 This is used for various commands in shell mode.
6030 If CURRENT_GROUP is lambda, that means send to the process group
6031 that currently owns the terminal, but only if it is NOT the shell itself.
6032
6033 If NOMSG is zero, insert signal-announcements into process's buffers
6034 right away.
6035
6036 If we can, we try to signal PROCESS by sending control characters
6037 down the pty. This allows us to signal inferiors who have changed
6038 their uid, for which killpg would return an EPERM error. */
6039
6040 static void
6041 process_send_signal (process, signo, current_group, nomsg)
6042 Lisp_Object process;
6043 int signo;
6044 Lisp_Object current_group;
6045 int nomsg;
6046 {
6047 Lisp_Object proc;
6048 register struct Lisp_Process *p;
6049 int gid;
6050 int no_pgrp = 0;
6051
6052 proc = get_process (process);
6053 p = XPROCESS (proc);
6054
6055 if (!EQ (p->type, Qreal))
6056 error ("Process %s is not a subprocess",
6057 SDATA (p->name));
6058 if (p->infd < 0)
6059 error ("Process %s is not active",
6060 SDATA (p->name));
6061
6062 if (!p->pty_flag)
6063 current_group = Qnil;
6064
6065 /* If we are using pgrps, get a pgrp number and make it negative. */
6066 if (NILP (current_group))
6067 /* Send the signal to the shell's process group. */
6068 gid = p->pid;
6069 else
6070 {
6071 #ifdef SIGNALS_VIA_CHARACTERS
6072 /* If possible, send signals to the entire pgrp
6073 by sending an input character to it. */
6074
6075 /* TERMIOS is the latest and bestest, and seems most likely to
6076 work. If the system has it, use it. */
6077 #ifdef HAVE_TERMIOS
6078 struct termios t;
6079 cc_t *sig_char = NULL;
6080
6081 tcgetattr (p->infd, &t);
6082
6083 switch (signo)
6084 {
6085 case SIGINT:
6086 sig_char = &t.c_cc[VINTR];
6087 break;
6088
6089 case SIGQUIT:
6090 sig_char = &t.c_cc[VQUIT];
6091 break;
6092
6093 case SIGTSTP:
6094 #if defined (VSWTCH) && !defined (PREFER_VSUSP)
6095 sig_char = &t.c_cc[VSWTCH];
6096 #else
6097 sig_char = &t.c_cc[VSUSP];
6098 #endif
6099 break;
6100 }
6101
6102 if (sig_char && *sig_char != CDISABLE)
6103 {
6104 send_process (proc, sig_char, 1, Qnil);
6105 return;
6106 }
6107 /* If we can't send the signal with a character,
6108 fall through and send it another way. */
6109 #else /* ! HAVE_TERMIOS */
6110
6111 /* On Berkeley descendants, the following IOCTL's retrieve the
6112 current control characters. */
6113 #if defined (TIOCGLTC) && defined (TIOCGETC)
6114
6115 struct tchars c;
6116 struct ltchars lc;
6117
6118 switch (signo)
6119 {
6120 case SIGINT:
6121 ioctl (p->infd, TIOCGETC, &c);
6122 send_process (proc, &c.t_intrc, 1, Qnil);
6123 return;
6124 case SIGQUIT:
6125 ioctl (p->infd, TIOCGETC, &c);
6126 send_process (proc, &c.t_quitc, 1, Qnil);
6127 return;
6128 #ifdef SIGTSTP
6129 case SIGTSTP:
6130 ioctl (p->infd, TIOCGLTC, &lc);
6131 send_process (proc, &lc.t_suspc, 1, Qnil);
6132 return;
6133 #endif /* ! defined (SIGTSTP) */
6134 }
6135
6136 #else /* ! defined (TIOCGLTC) && defined (TIOCGETC) */
6137
6138 /* On SYSV descendants, the TCGETA ioctl retrieves the current control
6139 characters. */
6140 #ifdef TCGETA
6141 struct termio t;
6142 switch (signo)
6143 {
6144 case SIGINT:
6145 ioctl (p->infd, TCGETA, &t);
6146 send_process (proc, &t.c_cc[VINTR], 1, Qnil);
6147 return;
6148 case SIGQUIT:
6149 ioctl (p->infd, TCGETA, &t);
6150 send_process (proc, &t.c_cc[VQUIT], 1, Qnil);
6151 return;
6152 #ifdef SIGTSTP
6153 case SIGTSTP:
6154 ioctl (p->infd, TCGETA, &t);
6155 send_process (proc, &t.c_cc[VSWTCH], 1, Qnil);
6156 return;
6157 #endif /* ! defined (SIGTSTP) */
6158 }
6159 #else /* ! defined (TCGETA) */
6160 Your configuration files are messed up.
6161 /* If your system configuration files define SIGNALS_VIA_CHARACTERS,
6162 you'd better be using one of the alternatives above! */
6163 #endif /* ! defined (TCGETA) */
6164 #endif /* ! defined (TIOCGLTC) && defined (TIOCGETC) */
6165 /* In this case, the code above should alway return. */
6166 abort ();
6167 #endif /* ! defined HAVE_TERMIOS */
6168
6169 /* The code above may fall through if it can't
6170 handle the signal. */
6171 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
6172
6173 #ifdef TIOCGPGRP
6174 /* Get the current pgrp using the tty itself, if we have that.
6175 Otherwise, use the pty to get the pgrp.
6176 On pfa systems, saka@pfu.fujitsu.co.JP writes:
6177 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
6178 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
6179 His patch indicates that if TIOCGPGRP returns an error, then
6180 we should just assume that p->pid is also the process group id. */
6181
6182 gid = emacs_get_tty_pgrp (p);
6183
6184 if (gid == -1)
6185 /* If we can't get the information, assume
6186 the shell owns the tty. */
6187 gid = p->pid;
6188
6189 /* It is not clear whether anything really can set GID to -1.
6190 Perhaps on some system one of those ioctls can or could do so.
6191 Or perhaps this is vestigial. */
6192 if (gid == -1)
6193 no_pgrp = 1;
6194 #else /* ! defined (TIOCGPGRP ) */
6195 /* Can't select pgrps on this system, so we know that
6196 the child itself heads the pgrp. */
6197 gid = p->pid;
6198 #endif /* ! defined (TIOCGPGRP ) */
6199
6200 /* If current_group is lambda, and the shell owns the terminal,
6201 don't send any signal. */
6202 if (EQ (current_group, Qlambda) && gid == p->pid)
6203 return;
6204 }
6205
6206 switch (signo)
6207 {
6208 #ifdef SIGCONT
6209 case SIGCONT:
6210 p->raw_status_new = 0;
6211 p->status = Qrun;
6212 p->tick = ++process_tick;
6213 if (!nomsg)
6214 {
6215 status_notify (NULL);
6216 redisplay_preserve_echo_area (13);
6217 }
6218 break;
6219 #endif /* ! defined (SIGCONT) */
6220 case SIGINT:
6221 case SIGQUIT:
6222 case SIGKILL:
6223 flush_pending_output (p->infd);
6224 break;
6225 }
6226
6227 /* If we don't have process groups, send the signal to the immediate
6228 subprocess. That isn't really right, but it's better than any
6229 obvious alternative. */
6230 if (no_pgrp)
6231 {
6232 kill (p->pid, signo);
6233 return;
6234 }
6235
6236 /* gid may be a pid, or minus a pgrp's number */
6237 #ifdef TIOCSIGSEND
6238 if (!NILP (current_group))
6239 {
6240 if (ioctl (p->infd, TIOCSIGSEND, signo) == -1)
6241 EMACS_KILLPG (gid, signo);
6242 }
6243 else
6244 {
6245 gid = - p->pid;
6246 kill (gid, signo);
6247 }
6248 #else /* ! defined (TIOCSIGSEND) */
6249 EMACS_KILLPG (gid, signo);
6250 #endif /* ! defined (TIOCSIGSEND) */
6251 }
6252
6253 DEFUN ("interrupt-process", Finterrupt_process, Sinterrupt_process, 0, 2, 0,
6254 doc: /* Interrupt process PROCESS.
6255 PROCESS may be a process, a buffer, or the name of a process or buffer.
6256 No arg or nil means current buffer's process.
6257 Second arg CURRENT-GROUP non-nil means send signal to
6258 the current process-group of the process's controlling terminal
6259 rather than to the process's own process group.
6260 If the process is a shell, this means interrupt current subjob
6261 rather than the shell.
6262
6263 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
6264 don't send the signal. */)
6265 (process, current_group)
6266 Lisp_Object process, current_group;
6267 {
6268 process_send_signal (process, SIGINT, current_group, 0);
6269 return process;
6270 }
6271
6272 DEFUN ("kill-process", Fkill_process, Skill_process, 0, 2, 0,
6273 doc: /* Kill process PROCESS. May be process or name of one.
6274 See function `interrupt-process' for more details on usage. */)
6275 (process, current_group)
6276 Lisp_Object process, current_group;
6277 {
6278 process_send_signal (process, SIGKILL, current_group, 0);
6279 return process;
6280 }
6281
6282 DEFUN ("quit-process", Fquit_process, Squit_process, 0, 2, 0,
6283 doc: /* Send QUIT signal to process PROCESS. May be process or name of one.
6284 See function `interrupt-process' for more details on usage. */)
6285 (process, current_group)
6286 Lisp_Object process, current_group;
6287 {
6288 process_send_signal (process, SIGQUIT, current_group, 0);
6289 return process;
6290 }
6291
6292 DEFUN ("stop-process", Fstop_process, Sstop_process, 0, 2, 0,
6293 doc: /* Stop process PROCESS. May be process or name of one.
6294 See function `interrupt-process' for more details on usage.
6295 If PROCESS is a network or serial process, inhibit handling of incoming
6296 traffic. */)
6297 (process, current_group)
6298 Lisp_Object process, current_group;
6299 {
6300 #ifdef HAVE_SOCKETS
6301 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
6302 {
6303 struct Lisp_Process *p;
6304
6305 p = XPROCESS (process);
6306 if (NILP (p->command)
6307 && p->infd >= 0)
6308 {
6309 FD_CLR (p->infd, &input_wait_mask);
6310 FD_CLR (p->infd, &non_keyboard_wait_mask);
6311 }
6312 p->command = Qt;
6313 return process;
6314 }
6315 #endif
6316 #ifndef SIGTSTP
6317 error ("No SIGTSTP support");
6318 #else
6319 process_send_signal (process, SIGTSTP, current_group, 0);
6320 #endif
6321 return process;
6322 }
6323
6324 DEFUN ("continue-process", Fcontinue_process, Scontinue_process, 0, 2, 0,
6325 doc: /* Continue process PROCESS. May be process or name of one.
6326 See function `interrupt-process' for more details on usage.
6327 If PROCESS is a network or serial process, resume handling of incoming
6328 traffic. */)
6329 (process, current_group)
6330 Lisp_Object process, current_group;
6331 {
6332 #ifdef HAVE_SOCKETS
6333 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
6334 {
6335 struct Lisp_Process *p;
6336
6337 p = XPROCESS (process);
6338 if (EQ (p->command, Qt)
6339 && p->infd >= 0
6340 && (!EQ (p->filter, Qt) || EQ (p->status, Qlisten)))
6341 {
6342 FD_SET (p->infd, &input_wait_mask);
6343 FD_SET (p->infd, &non_keyboard_wait_mask);
6344 #ifdef WINDOWSNT
6345 if (fd_info[ p->infd ].flags & FILE_SERIAL)
6346 PurgeComm (fd_info[ p->infd ].hnd, PURGE_RXABORT | PURGE_RXCLEAR);
6347 #endif
6348 #ifdef HAVE_TERMIOS
6349 tcflush (p->infd, TCIFLUSH);
6350 #endif
6351 }
6352 p->command = Qnil;
6353 return process;
6354 }
6355 #endif
6356 #ifdef SIGCONT
6357 process_send_signal (process, SIGCONT, current_group, 0);
6358 #else
6359 error ("No SIGCONT support");
6360 #endif
6361 return process;
6362 }
6363
6364 DEFUN ("signal-process", Fsignal_process, Ssignal_process,
6365 2, 2, "sProcess (name or number): \nnSignal code: ",
6366 doc: /* Send PROCESS the signal with code SIGCODE.
6367 PROCESS may also be a number specifying the process id of the
6368 process to signal; in this case, the process need not be a child of
6369 this Emacs.
6370 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
6371 (process, sigcode)
6372 Lisp_Object process, sigcode;
6373 {
6374 pid_t pid;
6375
6376 if (INTEGERP (process))
6377 {
6378 pid = XINT (process);
6379 goto got_it;
6380 }
6381
6382 if (FLOATP (process))
6383 {
6384 pid = (pid_t) XFLOAT_DATA (process);
6385 goto got_it;
6386 }
6387
6388 if (STRINGP (process))
6389 {
6390 Lisp_Object tem;
6391 if (tem = Fget_process (process), NILP (tem))
6392 {
6393 pid = XINT (Fstring_to_number (process, make_number (10)));
6394 if (pid > 0)
6395 goto got_it;
6396 }
6397 process = tem;
6398 }
6399 else
6400 process = get_process (process);
6401
6402 if (NILP (process))
6403 return process;
6404
6405 CHECK_PROCESS (process);
6406 pid = XPROCESS (process)->pid;
6407 if (pid <= 0)
6408 error ("Cannot signal process %s", SDATA (XPROCESS (process)->name));
6409
6410 got_it:
6411
6412 #define parse_signal(NAME, VALUE) \
6413 else if (!xstrcasecmp (name, NAME)) \
6414 XSETINT (sigcode, VALUE)
6415
6416 if (INTEGERP (sigcode))
6417 ;
6418 else
6419 {
6420 unsigned char *name;
6421
6422 CHECK_SYMBOL (sigcode);
6423 name = SDATA (SYMBOL_NAME (sigcode));
6424
6425 if (!strncmp(name, "SIG", 3) || !strncmp(name, "sig", 3))
6426 name += 3;
6427
6428 if (0)
6429 ;
6430 #ifdef SIGUSR1
6431 parse_signal ("usr1", SIGUSR1);
6432 #endif
6433 #ifdef SIGUSR2
6434 parse_signal ("usr2", SIGUSR2);
6435 #endif
6436 #ifdef SIGTERM
6437 parse_signal ("term", SIGTERM);
6438 #endif
6439 #ifdef SIGHUP
6440 parse_signal ("hup", SIGHUP);
6441 #endif
6442 #ifdef SIGINT
6443 parse_signal ("int", SIGINT);
6444 #endif
6445 #ifdef SIGQUIT
6446 parse_signal ("quit", SIGQUIT);
6447 #endif
6448 #ifdef SIGILL
6449 parse_signal ("ill", SIGILL);
6450 #endif
6451 #ifdef SIGABRT
6452 parse_signal ("abrt", SIGABRT);
6453 #endif
6454 #ifdef SIGEMT
6455 parse_signal ("emt", SIGEMT);
6456 #endif
6457 #ifdef SIGKILL
6458 parse_signal ("kill", SIGKILL);
6459 #endif
6460 #ifdef SIGFPE
6461 parse_signal ("fpe", SIGFPE);
6462 #endif
6463 #ifdef SIGBUS
6464 parse_signal ("bus", SIGBUS);
6465 #endif
6466 #ifdef SIGSEGV
6467 parse_signal ("segv", SIGSEGV);
6468 #endif
6469 #ifdef SIGSYS
6470 parse_signal ("sys", SIGSYS);
6471 #endif
6472 #ifdef SIGPIPE
6473 parse_signal ("pipe", SIGPIPE);
6474 #endif
6475 #ifdef SIGALRM
6476 parse_signal ("alrm", SIGALRM);
6477 #endif
6478 #ifdef SIGURG
6479 parse_signal ("urg", SIGURG);
6480 #endif
6481 #ifdef SIGSTOP
6482 parse_signal ("stop", SIGSTOP);
6483 #endif
6484 #ifdef SIGTSTP
6485 parse_signal ("tstp", SIGTSTP);
6486 #endif
6487 #ifdef SIGCONT
6488 parse_signal ("cont", SIGCONT);
6489 #endif
6490 #ifdef SIGCHLD
6491 parse_signal ("chld", SIGCHLD);
6492 #endif
6493 #ifdef SIGTTIN
6494 parse_signal ("ttin", SIGTTIN);
6495 #endif
6496 #ifdef SIGTTOU
6497 parse_signal ("ttou", SIGTTOU);
6498 #endif
6499 #ifdef SIGIO
6500 parse_signal ("io", SIGIO);
6501 #endif
6502 #ifdef SIGXCPU
6503 parse_signal ("xcpu", SIGXCPU);
6504 #endif
6505 #ifdef SIGXFSZ
6506 parse_signal ("xfsz", SIGXFSZ);
6507 #endif
6508 #ifdef SIGVTALRM
6509 parse_signal ("vtalrm", SIGVTALRM);
6510 #endif
6511 #ifdef SIGPROF
6512 parse_signal ("prof", SIGPROF);
6513 #endif
6514 #ifdef SIGWINCH
6515 parse_signal ("winch", SIGWINCH);
6516 #endif
6517 #ifdef SIGINFO
6518 parse_signal ("info", SIGINFO);
6519 #endif
6520 else
6521 error ("Undefined signal name %s", name);
6522 }
6523
6524 #undef parse_signal
6525
6526 return make_number (kill (pid, XINT (sigcode)));
6527 }
6528
6529 DEFUN ("process-send-eof", Fprocess_send_eof, Sprocess_send_eof, 0, 1, 0,
6530 doc: /* Make PROCESS see end-of-file in its input.
6531 EOF comes after any text already sent to it.
6532 PROCESS may be a process, a buffer, the name of a process or buffer, or
6533 nil, indicating the current buffer's process.
6534 If PROCESS is a network connection, or is a process communicating
6535 through a pipe (as opposed to a pty), then you cannot send any more
6536 text to PROCESS after you call this function.
6537 If PROCESS is a serial process, wait until all output written to the
6538 process has been transmitted to the serial port. */)
6539 (process)
6540 Lisp_Object process;
6541 {
6542 Lisp_Object proc;
6543 struct coding_system *coding;
6544
6545 if (DATAGRAM_CONN_P (process))
6546 return process;
6547
6548 proc = get_process (process);
6549 coding = proc_encode_coding_system[XPROCESS (proc)->outfd];
6550
6551 /* Make sure the process is really alive. */
6552 if (XPROCESS (proc)->raw_status_new)
6553 update_status (XPROCESS (proc));
6554 if (! EQ (XPROCESS (proc)->status, Qrun))
6555 error ("Process %s not running", SDATA (XPROCESS (proc)->name));
6556
6557 if (CODING_REQUIRE_FLUSHING (coding))
6558 {
6559 coding->mode |= CODING_MODE_LAST_BLOCK;
6560 send_process (proc, "", 0, Qnil);
6561 }
6562
6563 if (XPROCESS (proc)->pty_flag)
6564 send_process (proc, "\004", 1, Qnil);
6565 else if (EQ (XPROCESS (proc)->type, Qserial))
6566 {
6567 #ifdef HAVE_TERMIOS
6568 if (tcdrain (XPROCESS (proc)->outfd) != 0)
6569 error ("tcdrain() failed: %s", emacs_strerror (errno));
6570 #endif
6571 /* Do nothing on Windows because writes are blocking. */
6572 }
6573 else
6574 {
6575 int old_outfd, new_outfd;
6576
6577 #ifdef HAVE_SHUTDOWN
6578 /* If this is a network connection, or socketpair is used
6579 for communication with the subprocess, call shutdown to cause EOF.
6580 (In some old system, shutdown to socketpair doesn't work.
6581 Then we just can't win.) */
6582 if (EQ (XPROCESS (proc)->type, Qnetwork)
6583 || XPROCESS (proc)->outfd == XPROCESS (proc)->infd)
6584 shutdown (XPROCESS (proc)->outfd, 1);
6585 /* In case of socketpair, outfd == infd, so don't close it. */
6586 if (XPROCESS (proc)->outfd != XPROCESS (proc)->infd)
6587 emacs_close (XPROCESS (proc)->outfd);
6588 #else /* not HAVE_SHUTDOWN */
6589 emacs_close (XPROCESS (proc)->outfd);
6590 #endif /* not HAVE_SHUTDOWN */
6591 new_outfd = emacs_open (NULL_DEVICE, O_WRONLY, 0);
6592 if (new_outfd < 0)
6593 abort ();
6594 old_outfd = XPROCESS (proc)->outfd;
6595
6596 if (!proc_encode_coding_system[new_outfd])
6597 proc_encode_coding_system[new_outfd]
6598 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
6599 bcopy (proc_encode_coding_system[old_outfd],
6600 proc_encode_coding_system[new_outfd],
6601 sizeof (struct coding_system));
6602 bzero (proc_encode_coding_system[old_outfd],
6603 sizeof (struct coding_system));
6604
6605 XPROCESS (proc)->outfd = new_outfd;
6606 }
6607 return process;
6608 }
6609
6610 /* Kill all processes associated with `buffer'.
6611 If `buffer' is nil, kill all processes */
6612
6613 void
6614 kill_buffer_processes (buffer)
6615 Lisp_Object buffer;
6616 {
6617 Lisp_Object tail, proc;
6618
6619 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6620 {
6621 proc = XCDR (XCAR (tail));
6622 if (PROCESSP (proc)
6623 && (NILP (buffer) || EQ (XPROCESS (proc)->buffer, buffer)))
6624 {
6625 if (NETCONN_P (proc) || SERIALCONN_P (proc))
6626 Fdelete_process (proc);
6627 else if (XPROCESS (proc)->infd >= 0)
6628 process_send_signal (proc, SIGHUP, Qnil, 1);
6629 }
6630 }
6631 }
6632 \f
6633 /* On receipt of a signal that a child status has changed, loop asking
6634 about children with changed statuses until the system says there
6635 are no more.
6636
6637 All we do is change the status; we do not run sentinels or print
6638 notifications. That is saved for the next time keyboard input is
6639 done, in order to avoid timing errors.
6640
6641 ** WARNING: this can be called during garbage collection.
6642 Therefore, it must not be fooled by the presence of mark bits in
6643 Lisp objects.
6644
6645 ** USG WARNING: Although it is not obvious from the documentation
6646 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6647 signal() before executing at least one wait(), otherwise the
6648 handler will be called again, resulting in an infinite loop. The
6649 relevant portion of the documentation reads "SIGCLD signals will be
6650 queued and the signal-catching function will be continually
6651 reentered until the queue is empty". Invoking signal() causes the
6652 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6653 Inc.
6654
6655 ** Malloc WARNING: This should never call malloc either directly or
6656 indirectly; if it does, that is a bug */
6657
6658 #ifdef SIGCHLD
6659 SIGTYPE
6660 sigchld_handler (signo)
6661 int signo;
6662 {
6663 int old_errno = errno;
6664 Lisp_Object proc;
6665 register struct Lisp_Process *p;
6666 extern EMACS_TIME *input_available_clear_time;
6667
6668 SIGNAL_THREAD_CHECK (signo);
6669
6670 while (1)
6671 {
6672 pid_t pid;
6673 int w;
6674 Lisp_Object tail;
6675
6676 #ifdef WNOHANG
6677 #ifndef WUNTRACED
6678 #define WUNTRACED 0
6679 #endif /* no WUNTRACED */
6680 /* Keep trying to get a status until we get a definitive result. */
6681 do
6682 {
6683 errno = 0;
6684 pid = wait3 (&w, WNOHANG | WUNTRACED, 0);
6685 }
6686 while (pid < 0 && errno == EINTR);
6687
6688 if (pid <= 0)
6689 {
6690 /* PID == 0 means no processes found, PID == -1 means a real
6691 failure. We have done all our job, so return. */
6692
6693 /* USG systems forget handlers when they are used;
6694 must reestablish each time */
6695 #if defined (USG) && !defined (POSIX_SIGNALS)
6696 signal (signo, sigchld_handler); /* WARNING - must come after wait3() */
6697 #endif
6698 errno = old_errno;
6699 return;
6700 }
6701 #else
6702 pid = wait (&w);
6703 #endif /* no WNOHANG */
6704
6705 /* Find the process that signaled us, and record its status. */
6706
6707 /* The process can have been deleted by Fdelete_process. */
6708 for (tail = deleted_pid_list; CONSP (tail); tail = XCDR (tail))
6709 {
6710 Lisp_Object xpid = XCAR (tail);
6711 if ((INTEGERP (xpid) && pid == (pid_t) XINT (xpid))
6712 || (FLOATP (xpid) && pid == (pid_t) XFLOAT_DATA (xpid)))
6713 {
6714 XSETCAR (tail, Qnil);
6715 goto sigchld_end_of_loop;
6716 }
6717 }
6718
6719 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6720 p = 0;
6721 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6722 {
6723 proc = XCDR (XCAR (tail));
6724 p = XPROCESS (proc);
6725 if (EQ (p->type, Qreal) && p->pid == pid)
6726 break;
6727 p = 0;
6728 }
6729
6730 /* Look for an asynchronous process whose pid hasn't been filled
6731 in yet. */
6732 if (p == 0)
6733 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6734 {
6735 proc = XCDR (XCAR (tail));
6736 p = XPROCESS (proc);
6737 if (p->pid == -1)
6738 break;
6739 p = 0;
6740 }
6741
6742 /* Change the status of the process that was found. */
6743 if (p != 0)
6744 {
6745 int clear_desc_flag = 0;
6746
6747 p->tick = ++process_tick;
6748 p->raw_status = w;
6749 p->raw_status_new = 1;
6750
6751 /* If process has terminated, stop waiting for its output. */
6752 if ((WIFSIGNALED (w) || WIFEXITED (w))
6753 && p->infd >= 0)
6754 clear_desc_flag = 1;
6755
6756 /* We use clear_desc_flag to avoid a compiler bug in Microsoft C. */
6757 if (clear_desc_flag)
6758 {
6759 FD_CLR (p->infd, &input_wait_mask);
6760 FD_CLR (p->infd, &non_keyboard_wait_mask);
6761 }
6762
6763 /* Tell wait_reading_process_output that it needs to wake up and
6764 look around. */
6765 if (input_available_clear_time)
6766 EMACS_SET_SECS_USECS (*input_available_clear_time, 0, 0);
6767 }
6768
6769 /* There was no asynchronous process found for that pid: we have
6770 a synchronous process. */
6771 else
6772 {
6773 synch_process_alive = 0;
6774
6775 /* Report the status of the synchronous process. */
6776 if (WIFEXITED (w))
6777 synch_process_retcode = WRETCODE (w);
6778 else if (WIFSIGNALED (w))
6779 synch_process_termsig = WTERMSIG (w);
6780
6781 /* Tell wait_reading_process_output that it needs to wake up and
6782 look around. */
6783 if (input_available_clear_time)
6784 EMACS_SET_SECS_USECS (*input_available_clear_time, 0, 0);
6785 }
6786
6787 sigchld_end_of_loop:
6788 ;
6789
6790 /* On some systems, we must return right away.
6791 If any more processes want to signal us, we will
6792 get another signal.
6793 Otherwise (on systems that have WNOHANG), loop around
6794 to use up all the processes that have something to tell us. */
6795 #if (defined WINDOWSNT \
6796 || (defined USG && !defined GNU_LINUX \
6797 && !(defined HPUX && defined WNOHANG)))
6798 #if defined (USG) && ! defined (POSIX_SIGNALS)
6799 signal (signo, sigchld_handler);
6800 #endif
6801 errno = old_errno;
6802 return;
6803 #endif /* USG, but not HPUX with WNOHANG */
6804 }
6805 }
6806 #endif /* SIGCHLD */
6807 \f
6808
6809 static Lisp_Object
6810 exec_sentinel_unwind (data)
6811 Lisp_Object data;
6812 {
6813 XPROCESS (XCAR (data))->sentinel = XCDR (data);
6814 return Qnil;
6815 }
6816
6817 static Lisp_Object
6818 exec_sentinel_error_handler (error)
6819 Lisp_Object error;
6820 {
6821 cmd_error_internal (error, "error in process sentinel: ");
6822 Vinhibit_quit = Qt;
6823 update_echo_area ();
6824 Fsleep_for (make_number (2), Qnil);
6825 return Qt;
6826 }
6827
6828 static void
6829 exec_sentinel (proc, reason)
6830 Lisp_Object proc, reason;
6831 {
6832 Lisp_Object sentinel, obuffer, odeactivate, okeymap;
6833 register struct Lisp_Process *p = XPROCESS (proc);
6834 int count = SPECPDL_INDEX ();
6835 int outer_running_asynch_code = running_asynch_code;
6836 int waiting = waiting_for_user_input_p;
6837
6838 if (inhibit_sentinels)
6839 return;
6840
6841 /* No need to gcpro these, because all we do with them later
6842 is test them for EQness, and none of them should be a string. */
6843 odeactivate = Vdeactivate_mark;
6844 XSETBUFFER (obuffer, current_buffer);
6845 okeymap = current_buffer->keymap;
6846
6847 sentinel = p->sentinel;
6848 if (NILP (sentinel))
6849 return;
6850
6851 /* Zilch the sentinel while it's running, to avoid recursive invocations;
6852 assure that it gets restored no matter how the sentinel exits. */
6853 p->sentinel = Qnil;
6854 record_unwind_protect (exec_sentinel_unwind, Fcons (proc, sentinel));
6855 /* Inhibit quit so that random quits don't screw up a running filter. */
6856 specbind (Qinhibit_quit, Qt);
6857 specbind (Qlast_nonmenu_event, Qt);
6858
6859 /* In case we get recursively called,
6860 and we already saved the match data nonrecursively,
6861 save the same match data in safely recursive fashion. */
6862 if (outer_running_asynch_code)
6863 {
6864 Lisp_Object tem;
6865 tem = Fmatch_data (Qnil, Qnil, Qnil);
6866 restore_search_regs ();
6867 record_unwind_save_match_data ();
6868 Fset_match_data (tem, Qt);
6869 }
6870
6871 /* For speed, if a search happens within this code,
6872 save the match data in a special nonrecursive fashion. */
6873 running_asynch_code = 1;
6874
6875 internal_condition_case_1 (read_process_output_call,
6876 Fcons (sentinel,
6877 Fcons (proc, Fcons (reason, Qnil))),
6878 !NILP (Vdebug_on_error) ? Qnil : Qerror,
6879 exec_sentinel_error_handler);
6880
6881 /* If we saved the match data nonrecursively, restore it now. */
6882 restore_search_regs ();
6883 running_asynch_code = outer_running_asynch_code;
6884
6885 Vdeactivate_mark = odeactivate;
6886
6887 /* Restore waiting_for_user_input_p as it was
6888 when we were called, in case the filter clobbered it. */
6889 waiting_for_user_input_p = waiting;
6890
6891 #if 0
6892 if (! EQ (Fcurrent_buffer (), obuffer)
6893 || ! EQ (current_buffer->keymap, okeymap))
6894 #endif
6895 /* But do it only if the caller is actually going to read events.
6896 Otherwise there's no need to make him wake up, and it could
6897 cause trouble (for example it would make sit_for return). */
6898 if (waiting_for_user_input_p == -1)
6899 record_asynch_buffer_change ();
6900
6901 unbind_to (count, Qnil);
6902 }
6903
6904 /* Report all recent events of a change in process status
6905 (either run the sentinel or output a message).
6906 This is usually done while Emacs is waiting for keyboard input
6907 but can be done at other times. */
6908
6909 static void
6910 status_notify (deleting_process)
6911 struct Lisp_Process *deleting_process;
6912 {
6913 register Lisp_Object proc, buffer;
6914 Lisp_Object tail, msg;
6915 struct gcpro gcpro1, gcpro2;
6916
6917 tail = Qnil;
6918 msg = Qnil;
6919 /* We need to gcpro tail; if read_process_output calls a filter
6920 which deletes a process and removes the cons to which tail points
6921 from Vprocess_alist, and then causes a GC, tail is an unprotected
6922 reference. */
6923 GCPRO2 (tail, msg);
6924
6925 /* Set this now, so that if new processes are created by sentinels
6926 that we run, we get called again to handle their status changes. */
6927 update_tick = process_tick;
6928
6929 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6930 {
6931 Lisp_Object symbol;
6932 register struct Lisp_Process *p;
6933
6934 proc = Fcdr (XCAR (tail));
6935 p = XPROCESS (proc);
6936
6937 if (p->tick != p->update_tick)
6938 {
6939 p->update_tick = p->tick;
6940
6941 /* If process is still active, read any output that remains. */
6942 while (! EQ (p->filter, Qt)
6943 && ! EQ (p->status, Qconnect)
6944 && ! EQ (p->status, Qlisten)
6945 /* Network or serial process not stopped: */
6946 && ! EQ (p->command, Qt)
6947 && p->infd >= 0
6948 && p != deleting_process
6949 && read_process_output (proc, p->infd) > 0);
6950
6951 buffer = p->buffer;
6952
6953 /* Get the text to use for the message. */
6954 if (p->raw_status_new)
6955 update_status (p);
6956 msg = status_message (p);
6957
6958 /* If process is terminated, deactivate it or delete it. */
6959 symbol = p->status;
6960 if (CONSP (p->status))
6961 symbol = XCAR (p->status);
6962
6963 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
6964 || EQ (symbol, Qclosed))
6965 {
6966 if (delete_exited_processes)
6967 remove_process (proc);
6968 else
6969 deactivate_process (proc);
6970 }
6971
6972 /* The actions above may have further incremented p->tick.
6973 So set p->update_tick again
6974 so that an error in the sentinel will not cause
6975 this code to be run again. */
6976 p->update_tick = p->tick;
6977 /* Now output the message suitably. */
6978 if (!NILP (p->sentinel))
6979 exec_sentinel (proc, msg);
6980 /* Don't bother with a message in the buffer
6981 when a process becomes runnable. */
6982 else if (!EQ (symbol, Qrun) && !NILP (buffer))
6983 {
6984 Lisp_Object ro, tem;
6985 struct buffer *old = current_buffer;
6986 int opoint, opoint_byte;
6987 int before, before_byte;
6988
6989 ro = XBUFFER (buffer)->read_only;
6990
6991 /* Avoid error if buffer is deleted
6992 (probably that's why the process is dead, too) */
6993 if (NILP (XBUFFER (buffer)->name))
6994 continue;
6995 Fset_buffer (buffer);
6996
6997 opoint = PT;
6998 opoint_byte = PT_BYTE;
6999 /* Insert new output into buffer
7000 at the current end-of-output marker,
7001 thus preserving logical ordering of input and output. */
7002 if (XMARKER (p->mark)->buffer)
7003 Fgoto_char (p->mark);
7004 else
7005 SET_PT_BOTH (ZV, ZV_BYTE);
7006
7007 before = PT;
7008 before_byte = PT_BYTE;
7009
7010 tem = current_buffer->read_only;
7011 current_buffer->read_only = Qnil;
7012 insert_string ("\nProcess ");
7013 Finsert (1, &p->name);
7014 insert_string (" ");
7015 Finsert (1, &msg);
7016 current_buffer->read_only = tem;
7017 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
7018
7019 if (opoint >= before)
7020 SET_PT_BOTH (opoint + (PT - before),
7021 opoint_byte + (PT_BYTE - before_byte));
7022 else
7023 SET_PT_BOTH (opoint, opoint_byte);
7024
7025 set_buffer_internal (old);
7026 }
7027 }
7028 } /* end for */
7029
7030 update_mode_lines++; /* in case buffers use %s in mode-line-format */
7031 UNGCPRO;
7032 }
7033
7034 \f
7035 DEFUN ("set-process-coding-system", Fset_process_coding_system,
7036 Sset_process_coding_system, 1, 3, 0,
7037 doc: /* Set coding systems of PROCESS to DECODING and ENCODING.
7038 DECODING will be used to decode subprocess output and ENCODING to
7039 encode subprocess input. */)
7040 (process, decoding, encoding)
7041 register Lisp_Object process, decoding, encoding;
7042 {
7043 register struct Lisp_Process *p;
7044
7045 CHECK_PROCESS (process);
7046 p = XPROCESS (process);
7047 if (p->infd < 0)
7048 error ("Input file descriptor of %s closed", SDATA (p->name));
7049 if (p->outfd < 0)
7050 error ("Output file descriptor of %s closed", SDATA (p->name));
7051 Fcheck_coding_system (decoding);
7052 Fcheck_coding_system (encoding);
7053 encoding = coding_inherit_eol_type (encoding, Qnil);
7054 p->decode_coding_system = decoding;
7055 p->encode_coding_system = encoding;
7056 setup_process_coding_systems (process);
7057
7058 return Qnil;
7059 }
7060
7061 DEFUN ("process-coding-system",
7062 Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
7063 doc: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
7064 (process)
7065 register Lisp_Object process;
7066 {
7067 CHECK_PROCESS (process);
7068 return Fcons (XPROCESS (process)->decode_coding_system,
7069 XPROCESS (process)->encode_coding_system);
7070 }
7071
7072 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte,
7073 Sset_process_filter_multibyte, 2, 2, 0,
7074 doc: /* Set multibyteness of the strings given to PROCESS's filter.
7075 If FLAG is non-nil, the filter is given multibyte strings.
7076 If FLAG is nil, the filter is given unibyte strings. In this case,
7077 all character code conversion except for end-of-line conversion is
7078 suppressed. */)
7079 (process, flag)
7080 Lisp_Object process, flag;
7081 {
7082 register struct Lisp_Process *p;
7083
7084 CHECK_PROCESS (process);
7085 p = XPROCESS (process);
7086 if (NILP (flag))
7087 p->decode_coding_system = raw_text_coding_system (p->decode_coding_system);
7088 setup_process_coding_systems (process);
7089
7090 return Qnil;
7091 }
7092
7093 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p,
7094 Sprocess_filter_multibyte_p, 1, 1, 0,
7095 doc: /* Return t if a multibyte string is given to PROCESS's filter.*/)
7096 (process)
7097 Lisp_Object process;
7098 {
7099 register struct Lisp_Process *p;
7100 struct coding_system *coding;
7101
7102 CHECK_PROCESS (process);
7103 p = XPROCESS (process);
7104 coding = proc_decode_coding_system[p->infd];
7105 return (CODING_FOR_UNIBYTE (coding) ? Qnil : Qt);
7106 }
7107
7108
7109 \f
7110 /* Add DESC to the set of keyboard input descriptors. */
7111
7112 void
7113 add_keyboard_wait_descriptor (desc)
7114 int desc;
7115 {
7116 FD_SET (desc, &input_wait_mask);
7117 FD_SET (desc, &non_process_wait_mask);
7118 if (desc > max_keyboard_desc)
7119 max_keyboard_desc = desc;
7120 }
7121
7122 static int add_gpm_wait_descriptor_called_flag;
7123
7124 void
7125 add_gpm_wait_descriptor (desc)
7126 int desc;
7127 {
7128 if (! add_gpm_wait_descriptor_called_flag)
7129 FD_CLR (0, &input_wait_mask);
7130 add_gpm_wait_descriptor_called_flag = 1;
7131 FD_SET (desc, &input_wait_mask);
7132 FD_SET (desc, &gpm_wait_mask);
7133 if (desc > max_gpm_desc)
7134 max_gpm_desc = desc;
7135 }
7136
7137 /* From now on, do not expect DESC to give keyboard input. */
7138
7139 void
7140 delete_keyboard_wait_descriptor (desc)
7141 int desc;
7142 {
7143 int fd;
7144 int lim = max_keyboard_desc;
7145
7146 FD_CLR (desc, &input_wait_mask);
7147 FD_CLR (desc, &non_process_wait_mask);
7148
7149 if (desc == max_keyboard_desc)
7150 for (fd = 0; fd < lim; fd++)
7151 if (FD_ISSET (fd, &input_wait_mask)
7152 && !FD_ISSET (fd, &non_keyboard_wait_mask)
7153 && !FD_ISSET (fd, &gpm_wait_mask))
7154 max_keyboard_desc = fd;
7155 }
7156
7157 void
7158 delete_gpm_wait_descriptor (desc)
7159 int desc;
7160 {
7161 int fd;
7162 int lim = max_gpm_desc;
7163
7164 FD_CLR (desc, &input_wait_mask);
7165 FD_CLR (desc, &non_process_wait_mask);
7166
7167 if (desc == max_gpm_desc)
7168 for (fd = 0; fd < lim; fd++)
7169 if (FD_ISSET (fd, &input_wait_mask)
7170 && !FD_ISSET (fd, &non_keyboard_wait_mask)
7171 && !FD_ISSET (fd, &non_process_wait_mask))
7172 max_gpm_desc = fd;
7173 }
7174
7175 /* Return nonzero if *MASK has a bit set
7176 that corresponds to one of the keyboard input descriptors. */
7177
7178 static int
7179 keyboard_bit_set (mask)
7180 SELECT_TYPE *mask;
7181 {
7182 int fd;
7183
7184 for (fd = 0; fd <= max_keyboard_desc; fd++)
7185 if (FD_ISSET (fd, mask) && FD_ISSET (fd, &input_wait_mask)
7186 && !FD_ISSET (fd, &non_keyboard_wait_mask))
7187 return 1;
7188
7189 return 0;
7190 }
7191 \f
7192 /* Enumeration of and access to system processes a-la ps(1). */
7193
7194 DEFUN ("list-system-processes", Flist_system_processes, Slist_system_processes,
7195 0, 0, 0,
7196 doc: /* Return a list of numerical process IDs of all running processes.
7197 If this functionality is unsupported, return nil.
7198
7199 See `process-attributes' for getting attributes of a process given its ID. */)
7200 ()
7201 {
7202 return list_system_processes ();
7203 }
7204
7205 DEFUN ("process-attributes", Fprocess_attributes,
7206 Sprocess_attributes, 1, 1, 0,
7207 doc: /* Return attributes of the process given by its PID, a number.
7208
7209 Value is an alist where each element is a cons cell of the form
7210
7211 \(KEY . VALUE)
7212
7213 If this functionality is unsupported, the value is nil.
7214
7215 See `list-system-processes' for getting a list of all process IDs.
7216
7217 The KEYs of the attributes that this function may return are listed
7218 below, together with the type of the associated VALUE (in parentheses).
7219 Not all platforms support all of these attributes; unsupported
7220 attributes will not appear in the returned alist.
7221 Unless explicitly indicated otherwise, numbers can have either
7222 integer or floating point values.
7223
7224 euid -- Effective user User ID of the process (number)
7225 user -- User name corresponding to euid (string)
7226 egid -- Effective user Group ID of the process (number)
7227 group -- Group name corresponding to egid (string)
7228 comm -- Command name (executable name only) (string)
7229 state -- Process state code, such as "S", "R", or "T" (string)
7230 ppid -- Parent process ID (number)
7231 pgrp -- Process group ID (number)
7232 sess -- Session ID, i.e. process ID of session leader (number)
7233 ttname -- Controlling tty name (string)
7234 tpgid -- ID of foreground process group on the process's tty (number)
7235 minflt -- number of minor page faults (number)
7236 majflt -- number of major page faults (number)
7237 cminflt -- cumulative number of minor page faults (number)
7238 cmajflt -- cumulative number of major page faults (number)
7239 utime -- user time used by the process, in the (HIGH LOW USEC) format
7240 stime -- system time used by the process, in the (HIGH LOW USEC) format
7241 time -- sum of utime and stime, in the (HIGH LOW USEC) format
7242 cutime -- user time used by the process and its children, (HIGH LOW USEC)
7243 cstime -- system time used by the process and its children, (HIGH LOW USEC)
7244 ctime -- sum of cutime and cstime, in the (HIGH LOW USEC) format
7245 pri -- priority of the process (number)
7246 nice -- nice value of the process (number)
7247 thcount -- process thread count (number)
7248 start -- time the process started, in the (HIGH LOW USEC) format
7249 vsize -- virtual memory size of the process in KB's (number)
7250 rss -- resident set size of the process in KB's (number)
7251 etime -- elapsed time the process is running, in (HIGH LOW USEC) format
7252 pcpu -- percents of CPU time used by the process (floating-point number)
7253 pmem -- percents of total physical memory used by process's resident set
7254 (floating-point number)
7255 args -- command line which invoked the process (string). */)
7256 (pid)
7257
7258 Lisp_Object pid;
7259 {
7260 return system_process_attributes (pid);
7261 }
7262 \f
7263 void
7264 init_process ()
7265 {
7266 register int i;
7267
7268 inhibit_sentinels = 0;
7269
7270 #ifdef SIGCHLD
7271 #ifndef CANNOT_DUMP
7272 if (! noninteractive || initialized)
7273 #endif
7274 signal (SIGCHLD, sigchld_handler);
7275 #endif
7276
7277 FD_ZERO (&input_wait_mask);
7278 FD_ZERO (&non_keyboard_wait_mask);
7279 FD_ZERO (&non_process_wait_mask);
7280 max_process_desc = 0;
7281
7282 #ifdef NON_BLOCKING_CONNECT
7283 FD_ZERO (&connect_wait_mask);
7284 num_pending_connects = 0;
7285 #endif
7286
7287 #ifdef ADAPTIVE_READ_BUFFERING
7288 process_output_delay_count = 0;
7289 process_output_skip = 0;
7290 #endif
7291
7292 /* Don't do this, it caused infinite select loops. The display
7293 method should call add_keyboard_wait_descriptor on stdin if it
7294 needs that. */
7295 #if 0
7296 FD_SET (0, &input_wait_mask);
7297 #endif
7298
7299 Vprocess_alist = Qnil;
7300 #ifdef SIGCHLD
7301 deleted_pid_list = Qnil;
7302 #endif
7303 for (i = 0; i < MAXDESC; i++)
7304 {
7305 chan_process[i] = Qnil;
7306 proc_buffered_char[i] = -1;
7307 }
7308 bzero (proc_decode_coding_system, sizeof proc_decode_coding_system);
7309 bzero (proc_encode_coding_system, sizeof proc_encode_coding_system);
7310 #ifdef DATAGRAM_SOCKETS
7311 bzero (datagram_address, sizeof datagram_address);
7312 #endif
7313
7314 #ifdef HAVE_SOCKETS
7315 {
7316 Lisp_Object subfeatures = Qnil;
7317 struct socket_options *sopt;
7318
7319 #define ADD_SUBFEATURE(key, val) \
7320 subfeatures = Fcons (Fcons (key, Fcons (val, Qnil)), subfeatures)
7321
7322 #ifdef NON_BLOCKING_CONNECT
7323 ADD_SUBFEATURE (QCnowait, Qt);
7324 #endif
7325 #ifdef DATAGRAM_SOCKETS
7326 ADD_SUBFEATURE (QCtype, Qdatagram);
7327 #endif
7328 #ifdef HAVE_LOCAL_SOCKETS
7329 ADD_SUBFEATURE (QCfamily, Qlocal);
7330 #endif
7331 ADD_SUBFEATURE (QCfamily, Qipv4);
7332 #ifdef AF_INET6
7333 ADD_SUBFEATURE (QCfamily, Qipv6);
7334 #endif
7335 #ifdef HAVE_GETSOCKNAME
7336 ADD_SUBFEATURE (QCservice, Qt);
7337 #endif
7338 #if defined(O_NONBLOCK) || defined(O_NDELAY)
7339 ADD_SUBFEATURE (QCserver, Qt);
7340 #endif
7341
7342 for (sopt = socket_options; sopt->name; sopt++)
7343 subfeatures = Fcons (intern (sopt->name), subfeatures);
7344
7345 Fprovide (intern ("make-network-process"), subfeatures);
7346 }
7347 #endif /* HAVE_SOCKETS */
7348
7349 #if defined (DARWIN_OS)
7350 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7351 processes. As such, we only change the default value. */
7352 if (initialized)
7353 {
7354 char *release = get_operating_system_release();
7355 if (!release || !release[0] || (release[0] < MIN_PTY_KERNEL_VERSION
7356 && release[1] == '.')) {
7357 Vprocess_connection_type = Qnil;
7358 }
7359 }
7360 #endif
7361 }
7362
7363 void
7364 syms_of_process ()
7365 {
7366 Qprocessp = intern ("processp");
7367 staticpro (&Qprocessp);
7368 Qrun = intern ("run");
7369 staticpro (&Qrun);
7370 Qstop = intern ("stop");
7371 staticpro (&Qstop);
7372 Qsignal = intern ("signal");
7373 staticpro (&Qsignal);
7374
7375 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7376 here again.
7377
7378 Qexit = intern ("exit");
7379 staticpro (&Qexit); */
7380
7381 Qopen = intern ("open");
7382 staticpro (&Qopen);
7383 Qclosed = intern ("closed");
7384 staticpro (&Qclosed);
7385 Qconnect = intern ("connect");
7386 staticpro (&Qconnect);
7387 Qfailed = intern ("failed");
7388 staticpro (&Qfailed);
7389 Qlisten = intern ("listen");
7390 staticpro (&Qlisten);
7391 Qlocal = intern ("local");
7392 staticpro (&Qlocal);
7393 Qipv4 = intern ("ipv4");
7394 staticpro (&Qipv4);
7395 #ifdef AF_INET6
7396 Qipv6 = intern ("ipv6");
7397 staticpro (&Qipv6);
7398 #endif
7399 Qdatagram = intern ("datagram");
7400 staticpro (&Qdatagram);
7401
7402 QCport = intern (":port");
7403 staticpro (&QCport);
7404 QCspeed = intern (":speed");
7405 staticpro (&QCspeed);
7406 QCprocess = intern (":process");
7407 staticpro (&QCprocess);
7408
7409 QCbytesize = intern (":bytesize");
7410 staticpro (&QCbytesize);
7411 QCstopbits = intern (":stopbits");
7412 staticpro (&QCstopbits);
7413 QCparity = intern (":parity");
7414 staticpro (&QCparity);
7415 Qodd = intern ("odd");
7416 staticpro (&Qodd);
7417 Qeven = intern ("even");
7418 staticpro (&Qeven);
7419 QCflowcontrol = intern (":flowcontrol");
7420 staticpro (&QCflowcontrol);
7421 Qhw = intern ("hw");
7422 staticpro (&Qhw);
7423 Qsw = intern ("sw");
7424 staticpro (&Qsw);
7425 QCsummary = intern (":summary");
7426 staticpro (&QCsummary);
7427
7428 Qreal = intern ("real");
7429 staticpro (&Qreal);
7430 Qnetwork = intern ("network");
7431 staticpro (&Qnetwork);
7432 Qserial = intern ("serial");
7433 staticpro (&Qserial);
7434
7435 QCname = intern (":name");
7436 staticpro (&QCname);
7437 QCbuffer = intern (":buffer");
7438 staticpro (&QCbuffer);
7439 QChost = intern (":host");
7440 staticpro (&QChost);
7441 QCservice = intern (":service");
7442 staticpro (&QCservice);
7443 QCtype = intern (":type");
7444 staticpro (&QCtype);
7445 QClocal = intern (":local");
7446 staticpro (&QClocal);
7447 QCremote = intern (":remote");
7448 staticpro (&QCremote);
7449 QCcoding = intern (":coding");
7450 staticpro (&QCcoding);
7451 QCserver = intern (":server");
7452 staticpro (&QCserver);
7453 QCnowait = intern (":nowait");
7454 staticpro (&QCnowait);
7455 QCsentinel = intern (":sentinel");
7456 staticpro (&QCsentinel);
7457 QClog = intern (":log");
7458 staticpro (&QClog);
7459 QCnoquery = intern (":noquery");
7460 staticpro (&QCnoquery);
7461 QCstop = intern (":stop");
7462 staticpro (&QCstop);
7463 QCoptions = intern (":options");
7464 staticpro (&QCoptions);
7465 QCplist = intern (":plist");
7466 staticpro (&QCplist);
7467
7468 Qlast_nonmenu_event = intern ("last-nonmenu-event");
7469 staticpro (&Qlast_nonmenu_event);
7470
7471 staticpro (&Vprocess_alist);
7472 #ifdef SIGCHLD
7473 staticpro (&deleted_pid_list);
7474 #endif
7475
7476 Qeuid = intern ("euid");
7477 staticpro (&Qeuid);
7478 Qegid = intern ("egid");
7479 staticpro (&Qegid);
7480 Quser = intern ("user");
7481 staticpro (&Quser);
7482 Qgroup = intern ("group");
7483 staticpro (&Qgroup);
7484 Qcomm = intern ("comm");
7485 staticpro (&Qcomm);
7486 Qstate = intern ("state");
7487 staticpro (&Qstate);
7488 Qppid = intern ("ppid");
7489 staticpro (&Qppid);
7490 Qpgrp = intern ("pgrp");
7491 staticpro (&Qpgrp);
7492 Qsess = intern ("sess");
7493 staticpro (&Qsess);
7494 Qttname = intern ("ttname");
7495 staticpro (&Qttname);
7496 Qtpgid = intern ("tpgid");
7497 staticpro (&Qtpgid);
7498 Qminflt = intern ("minflt");
7499 staticpro (&Qminflt);
7500 Qmajflt = intern ("majflt");
7501 staticpro (&Qmajflt);
7502 Qcminflt = intern ("cminflt");
7503 staticpro (&Qcminflt);
7504 Qcmajflt = intern ("cmajflt");
7505 staticpro (&Qcmajflt);
7506 Qutime = intern ("utime");
7507 staticpro (&Qutime);
7508 Qstime = intern ("stime");
7509 staticpro (&Qstime);
7510 Qtime = intern ("time");
7511 staticpro (&Qtime);
7512 Qcutime = intern ("cutime");
7513 staticpro (&Qcutime);
7514 Qcstime = intern ("cstime");
7515 staticpro (&Qcstime);
7516 Qctime = intern ("ctime");
7517 staticpro (&Qctime);
7518 Qpri = intern ("pri");
7519 staticpro (&Qpri);
7520 Qnice = intern ("nice");
7521 staticpro (&Qnice);
7522 Qthcount = intern ("thcount");
7523 staticpro (&Qthcount);
7524 Qstart = intern ("start");
7525 staticpro (&Qstart);
7526 Qvsize = intern ("vsize");
7527 staticpro (&Qvsize);
7528 Qrss = intern ("rss");
7529 staticpro (&Qrss);
7530 Qetime = intern ("etime");
7531 staticpro (&Qetime);
7532 Qpcpu = intern ("pcpu");
7533 staticpro (&Qpcpu);
7534 Qpmem = intern ("pmem");
7535 staticpro (&Qpmem);
7536 Qargs = intern ("args");
7537 staticpro (&Qargs);
7538
7539 DEFVAR_BOOL ("delete-exited-processes", &delete_exited_processes,
7540 doc: /* *Non-nil means delete processes immediately when they exit.
7541 A value of nil means don't delete them until `list-processes' is run. */);
7542
7543 delete_exited_processes = 1;
7544
7545 DEFVAR_LISP ("process-connection-type", &Vprocess_connection_type,
7546 doc: /* Control type of device used to communicate with subprocesses.
7547 Values are nil to use a pipe, or t or `pty' to use a pty.
7548 The value has no effect if the system has no ptys or if all ptys are busy:
7549 then a pipe is used in any case.
7550 The value takes effect when `start-process' is called. */);
7551 Vprocess_connection_type = Qt;
7552
7553 #ifdef ADAPTIVE_READ_BUFFERING
7554 DEFVAR_LISP ("process-adaptive-read-buffering", &Vprocess_adaptive_read_buffering,
7555 doc: /* If non-nil, improve receive buffering by delaying after short reads.
7556 On some systems, when Emacs reads the output from a subprocess, the output data
7557 is read in very small blocks, potentially resulting in very poor performance.
7558 This behavior can be remedied to some extent by setting this variable to a
7559 non-nil value, as it will automatically delay reading from such processes, to
7560 allow them to produce more output before Emacs tries to read it.
7561 If the value is t, the delay is reset after each write to the process; any other
7562 non-nil value means that the delay is not reset on write.
7563 The variable takes effect when `start-process' is called. */);
7564 Vprocess_adaptive_read_buffering = Qt;
7565 #endif
7566
7567 defsubr (&Sprocessp);
7568 defsubr (&Sget_process);
7569 defsubr (&Sget_buffer_process);
7570 defsubr (&Sdelete_process);
7571 defsubr (&Sprocess_status);
7572 defsubr (&Sprocess_exit_status);
7573 defsubr (&Sprocess_id);
7574 defsubr (&Sprocess_name);
7575 defsubr (&Sprocess_tty_name);
7576 defsubr (&Sprocess_command);
7577 defsubr (&Sset_process_buffer);
7578 defsubr (&Sprocess_buffer);
7579 defsubr (&Sprocess_mark);
7580 defsubr (&Sset_process_filter);
7581 defsubr (&Sprocess_filter);
7582 defsubr (&Sset_process_sentinel);
7583 defsubr (&Sprocess_sentinel);
7584 defsubr (&Sset_process_window_size);
7585 defsubr (&Sset_process_inherit_coding_system_flag);
7586 defsubr (&Sprocess_inherit_coding_system_flag);
7587 defsubr (&Sset_process_query_on_exit_flag);
7588 defsubr (&Sprocess_query_on_exit_flag);
7589 defsubr (&Sprocess_contact);
7590 defsubr (&Sprocess_plist);
7591 defsubr (&Sset_process_plist);
7592 defsubr (&Slist_processes);
7593 defsubr (&Sprocess_list);
7594 defsubr (&Sstart_process);
7595 #ifdef HAVE_SERIAL
7596 defsubr (&Sserial_process_configure);
7597 defsubr (&Smake_serial_process);
7598 #endif /* HAVE_SERIAL */
7599 #ifdef HAVE_SOCKETS
7600 defsubr (&Sset_network_process_option);
7601 defsubr (&Smake_network_process);
7602 defsubr (&Sformat_network_address);
7603 #endif /* HAVE_SOCKETS */
7604 #if defined(HAVE_SOCKETS) && defined(HAVE_NET_IF_H) && defined(HAVE_SYS_IOCTL_H)
7605 #ifdef SIOCGIFCONF
7606 defsubr (&Snetwork_interface_list);
7607 #endif
7608 #if defined(SIOCGIFADDR) || defined(SIOCGIFHWADDR) || defined(SIOCGIFFLAGS)
7609 defsubr (&Snetwork_interface_info);
7610 #endif
7611 #endif /* HAVE_SOCKETS ... */
7612 #ifdef DATAGRAM_SOCKETS
7613 defsubr (&Sprocess_datagram_address);
7614 defsubr (&Sset_process_datagram_address);
7615 #endif
7616 defsubr (&Saccept_process_output);
7617 defsubr (&Sprocess_send_region);
7618 defsubr (&Sprocess_send_string);
7619 defsubr (&Sinterrupt_process);
7620 defsubr (&Skill_process);
7621 defsubr (&Squit_process);
7622 defsubr (&Sstop_process);
7623 defsubr (&Scontinue_process);
7624 defsubr (&Sprocess_running_child_p);
7625 defsubr (&Sprocess_send_eof);
7626 defsubr (&Ssignal_process);
7627 defsubr (&Swaiting_for_user_input_p);
7628 defsubr (&Sprocess_type);
7629 defsubr (&Sset_process_coding_system);
7630 defsubr (&Sprocess_coding_system);
7631 defsubr (&Sset_process_filter_multibyte);
7632 defsubr (&Sprocess_filter_multibyte_p);
7633 defsubr (&Slist_system_processes);
7634 defsubr (&Sprocess_attributes);
7635 }
7636
7637 \f
7638 #else /* not subprocesses */
7639
7640 #include <sys/types.h>
7641 #include <errno.h>
7642 #include <sys/stat.h>
7643 #include <stdlib.h>
7644 #include <fcntl.h>
7645 #include <setjmp.h>
7646 #ifdef HAVE_UNISTD_H
7647 #include <unistd.h>
7648 #endif
7649
7650 #include "lisp.h"
7651 #include "systime.h"
7652 #include "character.h"
7653 #include "coding.h"
7654 #include "termopts.h"
7655 #include "sysselect.h"
7656
7657 extern int frame_garbaged;
7658
7659 extern EMACS_TIME timer_check ();
7660 extern int timers_run;
7661
7662 Lisp_Object QCtype, QCname;
7663
7664 Lisp_Object Qeuid, Qegid, Qcomm, Qstate, Qppid, Qpgrp, Qsess, Qttname, Qtpgid;
7665 Lisp_Object Qminflt, Qmajflt, Qcminflt, Qcmajflt, Qutime, Qstime, Qcstime;
7666 Lisp_Object Qcutime, Qpri, Qnice, Qthcount, Qstart, Qvsize, Qrss, Qargs;
7667 Lisp_Object Quser, Qgroup, Qetime, Qpcpu, Qpmem, Qtime, Qctime;
7668
7669 /* As described above, except assuming that there are no subprocesses:
7670
7671 Wait for timeout to elapse and/or keyboard input to be available.
7672
7673 time_limit is:
7674 timeout in seconds, or
7675 zero for no limit, or
7676 -1 means gobble data immediately available but don't wait for any.
7677
7678 read_kbd is a Lisp_Object:
7679 0 to ignore keyboard input, or
7680 1 to return when input is available, or
7681 -1 means caller will actually read the input, so don't throw to
7682 the quit handler.
7683
7684 see full version for other parameters. We know that wait_proc will
7685 always be NULL, since `subprocesses' isn't defined.
7686
7687 do_display != 0 means redisplay should be done to show subprocess
7688 output that arrives.
7689
7690 Return true if we received input from any process. */
7691
7692 int
7693 wait_reading_process_output (time_limit, microsecs, read_kbd, do_display,
7694 wait_for_cell, wait_proc, just_wait_proc)
7695 int time_limit, microsecs, read_kbd, do_display;
7696 Lisp_Object wait_for_cell;
7697 struct Lisp_Process *wait_proc;
7698 int just_wait_proc;
7699 {
7700 register int nfds;
7701 EMACS_TIME end_time, timeout;
7702 SELECT_TYPE waitchannels;
7703 int xerrno;
7704
7705 /* What does time_limit really mean? */
7706 if (time_limit || microsecs)
7707 {
7708 EMACS_GET_TIME (end_time);
7709 EMACS_SET_SECS_USECS (timeout, time_limit, microsecs);
7710 EMACS_ADD_TIME (end_time, end_time, timeout);
7711 }
7712
7713 /* Turn off periodic alarms (in case they are in use)
7714 and then turn off any other atimers,
7715 because the select emulator uses alarms. */
7716 stop_polling ();
7717 turn_on_atimers (0);
7718
7719 while (1)
7720 {
7721 int timeout_reduced_for_timers = 0;
7722
7723 /* If calling from keyboard input, do not quit
7724 since we want to return C-g as an input character.
7725 Otherwise, do pending quit if requested. */
7726 if (read_kbd >= 0)
7727 QUIT;
7728
7729 /* Exit now if the cell we're waiting for became non-nil. */
7730 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7731 break;
7732
7733 /* Compute time from now till when time limit is up */
7734 /* Exit if already run out */
7735 if (time_limit == -1)
7736 {
7737 /* -1 specified for timeout means
7738 gobble output available now
7739 but don't wait at all. */
7740
7741 EMACS_SET_SECS_USECS (timeout, 0, 0);
7742 }
7743 else if (time_limit || microsecs)
7744 {
7745 EMACS_GET_TIME (timeout);
7746 EMACS_SUB_TIME (timeout, end_time, timeout);
7747 if (EMACS_TIME_NEG_P (timeout))
7748 break;
7749 }
7750 else
7751 {
7752 EMACS_SET_SECS_USECS (timeout, 100000, 0);
7753 }
7754
7755 /* If our caller will not immediately handle keyboard events,
7756 run timer events directly.
7757 (Callers that will immediately read keyboard events
7758 call timer_delay on their own.) */
7759 if (NILP (wait_for_cell))
7760 {
7761 EMACS_TIME timer_delay;
7762
7763 do
7764 {
7765 int old_timers_run = timers_run;
7766 timer_delay = timer_check (1);
7767 if (timers_run != old_timers_run && do_display)
7768 /* We must retry, since a timer may have requeued itself
7769 and that could alter the time delay. */
7770 redisplay_preserve_echo_area (14);
7771 else
7772 break;
7773 }
7774 while (!detect_input_pending ());
7775
7776 /* If there is unread keyboard input, also return. */
7777 if (read_kbd != 0
7778 && requeued_events_pending_p ())
7779 break;
7780
7781 if (! EMACS_TIME_NEG_P (timer_delay) && time_limit != -1)
7782 {
7783 EMACS_TIME difference;
7784 EMACS_SUB_TIME (difference, timer_delay, timeout);
7785 if (EMACS_TIME_NEG_P (difference))
7786 {
7787 timeout = timer_delay;
7788 timeout_reduced_for_timers = 1;
7789 }
7790 }
7791 }
7792
7793 /* Cause C-g and alarm signals to take immediate action,
7794 and cause input available signals to zero out timeout. */
7795 if (read_kbd < 0)
7796 set_waiting_for_input (&timeout);
7797
7798 /* Wait till there is something to do. */
7799
7800 if (! read_kbd && NILP (wait_for_cell))
7801 FD_ZERO (&waitchannels);
7802 else
7803 FD_SET (0, &waitchannels);
7804
7805 /* If a frame has been newly mapped and needs updating,
7806 reprocess its display stuff. */
7807 if (frame_garbaged && do_display)
7808 {
7809 clear_waiting_for_input ();
7810 redisplay_preserve_echo_area (15);
7811 if (read_kbd < 0)
7812 set_waiting_for_input (&timeout);
7813 }
7814
7815 if (read_kbd && detect_input_pending ())
7816 {
7817 nfds = 0;
7818 FD_ZERO (&waitchannels);
7819 }
7820 else
7821 nfds = select (1, &waitchannels, (SELECT_TYPE *)0, (SELECT_TYPE *)0,
7822 &timeout);
7823
7824 xerrno = errno;
7825
7826 /* Make C-g and alarm signals set flags again */
7827 clear_waiting_for_input ();
7828
7829 /* If we woke up due to SIGWINCH, actually change size now. */
7830 do_pending_window_change (0);
7831
7832 if (time_limit && nfds == 0 && ! timeout_reduced_for_timers)
7833 /* We waited the full specified time, so return now. */
7834 break;
7835
7836 if (nfds == -1)
7837 {
7838 /* If the system call was interrupted, then go around the
7839 loop again. */
7840 if (xerrno == EINTR)
7841 FD_ZERO (&waitchannels);
7842 else
7843 error ("select error: %s", emacs_strerror (xerrno));
7844 }
7845 #ifdef SOLARIS2
7846 else if (nfds > 0 && (waitchannels & 1) && interrupt_input)
7847 /* System sometimes fails to deliver SIGIO. */
7848 kill (getpid (), SIGIO);
7849 #endif
7850 #ifdef SIGIO
7851 if (read_kbd && interrupt_input && (waitchannels & 1))
7852 kill (getpid (), SIGIO);
7853 #endif
7854
7855 /* Check for keyboard input */
7856
7857 if (read_kbd
7858 && detect_input_pending_run_timers (do_display))
7859 {
7860 swallow_events (do_display);
7861 if (detect_input_pending_run_timers (do_display))
7862 break;
7863 }
7864
7865 /* If there is unread keyboard input, also return. */
7866 if (read_kbd
7867 && requeued_events_pending_p ())
7868 break;
7869
7870 /* If wait_for_cell. check for keyboard input
7871 but don't run any timers.
7872 ??? (It seems wrong to me to check for keyboard
7873 input at all when wait_for_cell, but the code
7874 has been this way since July 1994.
7875 Try changing this after version 19.31.) */
7876 if (! NILP (wait_for_cell)
7877 && detect_input_pending ())
7878 {
7879 swallow_events (do_display);
7880 if (detect_input_pending ())
7881 break;
7882 }
7883
7884 /* Exit now if the cell we're waiting for became non-nil. */
7885 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7886 break;
7887 }
7888
7889 start_polling ();
7890
7891 return 0;
7892 }
7893
7894
7895 /* Don't confuse make-docfile by having two doc strings for this function.
7896 make-docfile does not pay attention to #if, for good reason! */
7897 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
7898 0)
7899 (name)
7900 register Lisp_Object name;
7901 {
7902 return Qnil;
7903 }
7904
7905 /* Don't confuse make-docfile by having two doc strings for this function.
7906 make-docfile does not pay attention to #if, for good reason! */
7907 DEFUN ("process-inherit-coding-system-flag",
7908 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
7909 1, 1, 0,
7910 0)
7911 (process)
7912 register Lisp_Object process;
7913 {
7914 /* Ignore the argument and return the value of
7915 inherit-process-coding-system. */
7916 return inherit_process_coding_system ? Qt : Qnil;
7917 }
7918
7919 /* Kill all processes associated with `buffer'.
7920 If `buffer' is nil, kill all processes.
7921 Since we have no subprocesses, this does nothing. */
7922
7923 void
7924 kill_buffer_processes (buffer)
7925 Lisp_Object buffer;
7926 {
7927 }
7928
7929 DEFUN ("list-system-processes", Flist_system_processes, Slist_system_processes,
7930 0, 0, 0,
7931 doc: /* Return a list of numerical process IDs of all running processes.
7932 If this functionality is unsupported, return nil.
7933
7934 See `process-attributes' for getting attributes of a process given its ID. */)
7935 ()
7936 {
7937 return list_system_processes ();
7938 }
7939
7940 DEFUN ("process-attributes", Fprocess_attributes,
7941 Sprocess_attributes, 1, 1, 0,
7942 doc: /* Return attributes of the process given by its PID, a number.
7943
7944 Value is an alist where each element is a cons cell of the form
7945
7946 \(KEY . VALUE)
7947
7948 If this functionality is unsupported, the value is nil.
7949
7950 See `list-system-processes' for getting a list of all process IDs.
7951
7952 The KEYs of the attributes that this function may return are listed
7953 below, together with the type of the associated VALUE (in parentheses).
7954 Not all platforms support all of these attributes; unsupported
7955 attributes will not appear in the returned alist.
7956 Unless explicitly indicated otherwise, numbers can have either
7957 integer or floating point values.
7958
7959 euid -- Effective user User ID of the process (number)
7960 user -- User name corresponding to euid (string)
7961 egid -- Effective user Group ID of the process (number)
7962 group -- Group name corresponding to egid (string)
7963 comm -- Command name (executable name only) (string)
7964 state -- Process state code, such as "S", "R", or "T" (string)
7965 ppid -- Parent process ID (number)
7966 pgrp -- Process group ID (number)
7967 sess -- Session ID, i.e. process ID of session leader (number)
7968 ttname -- Controlling tty name (string)
7969 tpgid -- ID of foreground process group on the process's tty (number)
7970 minflt -- number of minor page faults (number)
7971 majflt -- number of major page faults (number)
7972 cminflt -- cumulative number of minor page faults (number)
7973 cmajflt -- cumulative number of major page faults (number)
7974 utime -- user time used by the process, in the (HIGH LOW USEC) format
7975 stime -- system time used by the process, in the (HIGH LOW USEC) format
7976 time -- sum of utime and stime, in the (HIGH LOW USEC) format
7977 cutime -- user time used by the process and its children, (HIGH LOW USEC)
7978 cstime -- system time used by the process and its children, (HIGH LOW USEC)
7979 ctime -- sum of cutime and cstime, in the (HIGH LOW USEC) format
7980 pri -- priority of the process (number)
7981 nice -- nice value of the process (number)
7982 thcount -- process thread count (number)
7983 start -- time the process started, in the (HIGH LOW USEC) format
7984 vsize -- virtual memory size of the process in KB's (number)
7985 rss -- resident set size of the process in KB's (number)
7986 etime -- elapsed time the process is running, in (HIGH LOW USEC) format
7987 pcpu -- percents of CPU time used by the process (floating-point number)
7988 pmem -- percents of total physical memory used by process's resident set
7989 (floating-point number)
7990 args -- command line which invoked the process (string). */)
7991 (pid)
7992
7993 Lisp_Object pid;
7994 {
7995 return system_process_attributes (pid);
7996 }
7997
7998 void
7999 init_process ()
8000 {
8001 }
8002
8003 void
8004 syms_of_process ()
8005 {
8006 QCtype = intern (":type");
8007 staticpro (&QCtype);
8008 QCname = intern (":name");
8009 staticpro (&QCname);
8010 QCtype = intern (":type");
8011 staticpro (&QCtype);
8012 QCname = intern (":name");
8013 staticpro (&QCname);
8014 Qeuid = intern ("euid");
8015 staticpro (&Qeuid);
8016 Qegid = intern ("egid");
8017 staticpro (&Qegid);
8018 Quser = intern ("user");
8019 staticpro (&Quser);
8020 Qgroup = intern ("group");
8021 staticpro (&Qgroup);
8022 Qcomm = intern ("comm");
8023 staticpro (&Qcomm);
8024 Qstate = intern ("state");
8025 staticpro (&Qstate);
8026 Qppid = intern ("ppid");
8027 staticpro (&Qppid);
8028 Qpgrp = intern ("pgrp");
8029 staticpro (&Qpgrp);
8030 Qsess = intern ("sess");
8031 staticpro (&Qsess);
8032 Qttname = intern ("ttname");
8033 staticpro (&Qttname);
8034 Qtpgid = intern ("tpgid");
8035 staticpro (&Qtpgid);
8036 Qminflt = intern ("minflt");
8037 staticpro (&Qminflt);
8038 Qmajflt = intern ("majflt");
8039 staticpro (&Qmajflt);
8040 Qcminflt = intern ("cminflt");
8041 staticpro (&Qcminflt);
8042 Qcmajflt = intern ("cmajflt");
8043 staticpro (&Qcmajflt);
8044 Qutime = intern ("utime");
8045 staticpro (&Qutime);
8046 Qstime = intern ("stime");
8047 staticpro (&Qstime);
8048 Qtime = intern ("time");
8049 staticpro (&Qtime);
8050 Qcutime = intern ("cutime");
8051 staticpro (&Qcutime);
8052 Qcstime = intern ("cstime");
8053 staticpro (&Qcstime);
8054 Qctime = intern ("ctime");
8055 staticpro (&Qctime);
8056 Qpri = intern ("pri");
8057 staticpro (&Qpri);
8058 Qnice = intern ("nice");
8059 staticpro (&Qnice);
8060 Qthcount = intern ("thcount");
8061 staticpro (&Qthcount);
8062 Qstart = intern ("start");
8063 staticpro (&Qstart);
8064 Qvsize = intern ("vsize");
8065 staticpro (&Qvsize);
8066 Qrss = intern ("rss");
8067 staticpro (&Qrss);
8068 Qetime = intern ("etime");
8069 staticpro (&Qetime);
8070 Qpcpu = intern ("pcpu");
8071 staticpro (&Qpcpu);
8072 Qpmem = intern ("pmem");
8073 staticpro (&Qpmem);
8074 Qargs = intern ("args");
8075 staticpro (&Qargs);
8076
8077 defsubr (&Sget_buffer_process);
8078 defsubr (&Sprocess_inherit_coding_system_flag);
8079 defsubr (&Slist_system_processes);
8080 defsubr (&Sprocess_attributes);
8081 }
8082
8083 \f
8084 #endif /* not subprocesses */
8085
8086 /* arch-tag: 3706c011-7b9a-4117-bd4f-59e7f701a4c4
8087 (do not change this comment) */