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