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