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