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