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